home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 March / macformat-022.iso / Shareware City / Developers / MA3.1.1 & CW4.5 / Modifications / *OR* replace these files / UApplication.cp < prev    next >
Encoding:
Text File  |  1994-09-17  |  154.4 KB  |  5,116 lines  |  [TEXT/MPS ]

  1. /*
  2. *    This file has been changed from the original MacApp 3.1.1
  3. *    to support the metrowerks CodeWarrior compilers C/C++ 1.1.1.
  4. *    These changes are known *not* to work with earlier versions
  5. *    of CodeWarrior.  Every attempt though has been made to to keep 
  6. *    this file compatible with other development environments.
  7. *
  8. *    Mark Anderson
  9. *    metrowerks
  10. *    9/16/94
  11. *
  12. */
  13.  
  14. //----------------------------------------------------------------------------------------
  15. // UApplication.cp 
  16. // Copyright © 1984-1994 by Apple Computer Inc. All rights reserved.
  17. //----------------------------------------------------------------------------------------
  18.  
  19.  
  20. #ifndef __UAPPLICATION__
  21. #include <UApplication.h>
  22. #endif
  23.  
  24. #ifndef __STDIO__
  25. #include <stdio.h>
  26. #endif
  27.  
  28. #ifndef __UGEOMETRY__
  29. #include <UGeometry.h>
  30. #endif
  31.  
  32. #ifndef __UBEHAVIOR__
  33. #include <UBehavior.h>
  34. #endif
  35.  
  36. #ifndef __UFILE__
  37. #include <UFile.h>
  38. #endif
  39.  
  40. #ifndef __UAPPLEEVENTS__
  41. #include <UAppleEvents.h>
  42. #endif
  43.  
  44. #ifndef __UPRINTHANDLER__
  45. #include <UPrintHandler.h>
  46. #endif
  47.  
  48. #ifndef __UWINDOW__
  49. #include <UWindow.h>
  50. #endif
  51.  
  52. #ifndef __USCROLLER__
  53. #include <UScroller.h>
  54. #endif
  55.  
  56. #ifndef __UDOCUMENT__
  57. #include <UDocument.h>
  58. #endif
  59.  
  60. #ifndef __UMACAPPUTILITIES__
  61. #include <UMacAppUtilities.h>
  62. #endif
  63.  
  64. #ifndef __UERRORMGR__
  65. #include <UErrorMgr.h>
  66. #endif
  67.  
  68. #ifndef __UMEMORY__
  69. #include <UMemory.h>
  70. #endif
  71.  
  72. #ifndef __UMENUMGR__
  73. #include <UMenuMgr.h>
  74. #endif
  75.  
  76. #ifndef __UMACAPPGLOBALS__
  77. #include <UMacAppGlobals.h>
  78. #endif
  79.  
  80. #ifndef __UDEPENDENCIES__
  81. #include "UDependencies.h"
  82. #endif
  83.  
  84. #ifndef __ERRORS__
  85. #include <Errors.h>
  86. #endif
  87.  
  88. #ifndef __TOOLUTILS__
  89. #include <ToolUtils.h>
  90. #endif
  91.  
  92. #ifndef __UBUSYCURSOR__
  93. #include <UBusyCursor.h>
  94. #endif
  95.  
  96. #ifndef __UDEBUG__
  97. #include <UDebug.h>
  98. #endif
  99.  
  100. #ifndef __UCLIPBOARDMGR__
  101. #include <UClipboardMgr.h>
  102. #endif
  103.  
  104. #ifndef __RESOURCES__
  105. #include <Resources.h>
  106. #endif
  107.  
  108. #ifndef __DESK__
  109. #include <Desk.h>
  110. #endif
  111.  
  112. #ifndef __PACKAGES__
  113. #include <Packages.h>
  114. #endif
  115.  
  116. #ifndef __SCRIPT__
  117. #include <Script.h>
  118. #endif
  119.  
  120. #ifndef __DISKINIT__
  121. #include <DiskInit.h>
  122. #endif
  123.  
  124. #ifndef __OSEVENTS__
  125. #include <OSEvents.h>
  126. #endif
  127.  
  128. #ifndef __ULOMEM__
  129. #include <ULoMem.h>
  130. #endif
  131.  
  132. #ifndef __STDLIB__
  133. #include <stdlib.h>
  134. #endif
  135.  
  136. #ifndef __UVIEWSERVER__
  137. #include <UViewServer.h>
  138. #endif
  139.  
  140. #ifndef __UTABBEHAVIORS__
  141. #include <UTabBehaviors.h>
  142. #endif
  143.  
  144. #ifndef __UPRINTING__
  145. #include <UPrinting.h>
  146. #endif
  147.  
  148. #ifndef __GESTALTEQU__
  149. #include <GestaltEqu.h>
  150. #endif
  151.  
  152. #ifndef __LOWMEM__
  153. #include <LowMem.h>
  154. #endif
  155.  
  156. #ifndef __DEVICES__
  157. #include <Devices.h>
  158. #endif
  159.  
  160. #if qNeedsVU
  161.     #ifndef __UVUASSIST__
  162.     #include <UVUAssist.h>
  163.     #endif
  164. #endif
  165.  
  166.  
  167. //----------------------------------------------------------------------------------------
  168. // Constant definitions
  169. //----------------------------------------------------------------------------------------
  170.  
  171. enum SystemJustification { smSysJustLeft = 0, smSysJustRight = -1 };
  172.     // Constants to use with GetSysDirection() and SetSysDirection().
  173.  
  174.  
  175. //----------------------------------------------------------------------------------------
  176. // Global variable definitions.
  177. //----------------------------------------------------------------------------------------
  178.  
  179. TApplication* gApplication = NULL;
  180. Boolean gInitialized = false;
  181. AEAddressDesc gServerAddress;
  182.  
  183.  
  184. Boolean hadCreditsStringList;        // does the rsrc 'STR#' == kDefaultCredits exist ?
  185. short lastCreditsStringIndex;        // the last CString in the STR# to be displayed
  186. long lastCreditsShownTicks;            // the tickcount when the last Credit was Shown
  187. CStringHandle originalText;            // the about box's original text (prior to credits)
  188. short waitTicks;                    // how long to wait between credits 
  189.  
  190. //========================================================================================
  191. // GLOBAL Procedures
  192. //========================================================================================
  193. #undef Inherited
  194.  
  195. //----------------------------------------------------------------------------------------
  196. // DoShowAboutAppFilter: 
  197. //----------------------------------------------------------------------------------------
  198. #pragma segment MAAboutApp
  199.  
  200. pascal Boolean DoShowAboutAppFilter(DialogPtr theDialog,
  201.                                     EventRecord& theEvent,
  202.                                     short& itemHit)
  203. {
  204.     CStr255 s;
  205.     CStr255 originalStr;
  206.     Handle item;
  207.     Boolean returnValue = false;
  208.     short itemType;
  209.     CRect box;
  210.  
  211.     switch (theEvent.what)
  212.     {
  213.         case keyDown:
  214.             switch ((unsigned char)(((theEvent.message) & charCodeMask)))
  215.             {
  216.                 case chEnter:
  217.                 case chReturn:
  218.                     DoAlertKeyDown(theDialog, ok);
  219.                     break;
  220.             }
  221.             break;
  222.  
  223.         case nullEvent:
  224.             if ((TickCount() - lastCreditsShownTicks) > waitTicks)
  225.             {
  226.                 short itemNo = 1;
  227.  
  228.                 do
  229.                 {
  230.                     item = NULL;
  231.                     GetDialogItem(theDialog, itemNo, &itemType, &item, box);
  232.                     if (((itemType) & 0x7F) == statText)// we don't care if its enabled or not 
  233.                         break;
  234.                     else
  235.                         ++itemNo;
  236.                 } while (item);
  237.  
  238.                 GetIndString(s, kDefaultCredits, lastCreditsStringIndex);
  239.  
  240.                 if (!s.IsEmpty())
  241.                 {
  242.                     // save the original text 
  243.                     if ((lastCreditsStringIndex == 1) && ((*originalText)->IsEmpty() && item))
  244.                     {
  245.                         GetDialogItemText(item, originalStr);
  246.                         SetString((StringHandle)originalText, (ConstStr255Param)&originalStr);
  247.                     }
  248.                     ++lastCreditsStringIndex;
  249.                     lastCreditsShownTicks = TickCount();
  250.                     if (item)
  251.                         SetDialogItemText(item, s);
  252.                     waitTicks = (short)Min((s.Length() * 6), 60);
  253.                 }
  254.                 else                            // no more items 
  255.                     {
  256.                         lastCreditsStringIndex = 1;
  257.                         lastCreditsShownTicks = TickCount();
  258.                         if (item)
  259.                         {
  260.                             BlockMove((*originalText), &originalStr, (**originalText).Length() + 1);
  261.                             SetDialogItemText(item, originalStr);
  262.                         }
  263.                         waitTicks = 6 * 60;
  264.                     }
  265.             }
  266.             break;
  267.     }                                            /* switch */
  268.  
  269.     // Forward on to the standard filter 
  270.     if (gMacAppAlertFilter)
  271.         returnValue = ((ModalFilterProcPtr)gMacAppAlertFilter)(theDialog, &theEvent, &itemHit);
  272.  
  273.     return returnValue;
  274. } // DoShowAboutAppFilter 
  275.  
  276. #if !qPowerPC
  277.  
  278. //----------------------------------------------------------------------------------------
  279. // IsOpen: 
  280. //----------------------------------------------------------------------------------------
  281. #pragma segment MASelCommand
  282.  
  283. typedef DCtlHandle UnitTable[129];
  284. typedef UnitTable* UnitTablePtr;
  285.  
  286. Boolean IsOpen(short itsID)
  287. {
  288.     DCtlHandle dceHnd;
  289.  
  290.     if ((itsID >= 0) && (itsID < GetUnitEntryCount()))
  291.     {
  292.         dceHnd = (*((UnitTablePtr)LMGetUTableBase()))[itsID];
  293.         return ((dceHnd) && ((((*dceHnd)->dCtlFlags) & 0x0400) != 0));
  294.     }
  295.     else
  296.         return false;
  297. } // IsOpen 
  298.  
  299. #endif
  300.  
  301. //========================================================================================
  302. // CLASS CEventListIterator
  303. //========================================================================================
  304. #undef Inherited
  305.  
  306. #pragma segment MAApplicationRes
  307.  
  308. class CEventListIterator : public CIterator
  309. {
  310. public:
  311.     // These items are currently public for searching
  312.  
  313.     ArrayIndex fCurrentIndex;                    // current index of this iteration
  314.  
  315. protected:
  316.     TEventList *fEventList;                        // the main event list
  317.  
  318. public:
  319.     CEventListIterator(TEventList* itsEventList);
  320.  
  321.     virtual Boolean More();        // override
  322.         // Returns true if there are more elements to iterate over
  323.  
  324.     TEvent* FirstEvent();
  325.         // Resets the iterator to begin again and returns the value of the first index in
  326.         // the iteration
  327.  
  328.     TEvent* NextEvent();
  329.         // Advances the iteration and then returns the index
  330.  
  331. protected:
  332.     virtual void Advance();        // override
  333.         // Advances the iteration
  334. };
  335.  
  336.  
  337. //----------------------------------------------------------------------------------------
  338. // CEventListIterator::CEventListIterator: 
  339. //----------------------------------------------------------------------------------------
  340. inline CEventListIterator::CEventListIterator(TEventList* itsEventList)
  341. {
  342.     fEventList = itsEventList;
  343.     fCurrentIndex = itsEventList->GetSize();    // We iterate backward over the event list
  344. } // CEventListIterator::CEventListIterator 
  345.  
  346. //----------------------------------------------------------------------------------------
  347. // CEventListIterator::FirstEvent: 
  348. //----------------------------------------------------------------------------------------
  349. inline TEvent* CEventListIterator::FirstEvent()
  350. {
  351.     if (this->More())
  352.         return (TEvent*)fEventList->At(fCurrentIndex);
  353.     else
  354.         return NULL;
  355. } // CEventListIterator::FirstEvent 
  356.  
  357. //----------------------------------------------------------------------------------------
  358. // CEventListIterator::NextEvent: 
  359. //----------------------------------------------------------------------------------------
  360. inline TEvent* CEventListIterator::NextEvent()
  361. {
  362.     this->Advance();
  363.     if (this->More())
  364.         return (TEvent*)fEventList->At(fCurrentIndex);
  365.     else
  366.         return NULL;
  367. } // CEventListIterator::NextEvent 
  368.  
  369. //----------------------------------------------------------------------------------------
  370. // CEventListIterator::Advance: 
  371. //----------------------------------------------------------------------------------------
  372. #pragma segment MAApplicationRes
  373.  
  374. void CEventListIterator::Advance()
  375. {
  376.     if (fCurrentIndex > 1)
  377.         --fCurrentIndex;
  378.     else
  379.         fCurrentIndex = kEmptyIndex;
  380. } // CEventListIterator::Advance 
  381.  
  382. //----------------------------------------------------------------------------------------
  383. // CEventListIterator::More: 
  384. //----------------------------------------------------------------------------------------
  385. #pragma segment MAApplicationRes
  386.  
  387. Boolean CEventListIterator::More()
  388. {
  389.     return (fCurrentIndex != kEmptyIndex);
  390. } // CEventListIterator::More 
  391.  
  392.  
  393. //========================================================================================
  394. // CLASS CDocumentIterator
  395. //========================================================================================
  396. #undef Inherited
  397.  
  398. //----------------------------------------------------------------------------------------
  399. // CDocumentIterator::CDocumentIterator: 
  400. //----------------------------------------------------------------------------------------
  401. #pragma segment MAApplicationRes
  402.  
  403. CDocumentIterator::CDocumentIterator(TApplication* itsApplication,
  404.                                      ArrayIndex itsLowBound,
  405.                                      ArrayIndex itsHighBound,
  406.                                      Boolean itsForward) :
  407.     CObjectIterator(itsApplication ? itsApplication->fDocumentList : NULL, itsLowBound, itsHighBound, itsForward)
  408.  
  409. {
  410. } // CDocumentIterator::CDocumentIterator 
  411.  
  412. //----------------------------------------------------------------------------------------
  413. // CDocumentIterator::CDocumentIterator: 
  414. //----------------------------------------------------------------------------------------
  415. #pragma segment MAApplicationRes
  416.  
  417. CDocumentIterator::CDocumentIterator(TApplication* itsApplication,
  418.                                      Boolean itsForward) :
  419.     CObjectIterator(itsApplication ? itsApplication->fDocumentList : NULL, itsForward)
  420. {
  421. } // CDocumentIterator::CDocumentIterator 
  422.  
  423. //----------------------------------------------------------------------------------------
  424. // CDocumentIterator::CDocumentIterator: 
  425. //----------------------------------------------------------------------------------------
  426. #pragma segment MAApplicationRes
  427.  
  428. CDocumentIterator::CDocumentIterator(TApplication* itsApplication) :
  429.     CObjectIterator(itsApplication ? itsApplication->fDocumentList : NULL)
  430. {
  431. } // CDocumentIterator::CDocumentIterator 
  432.  
  433. //----------------------------------------------------------------------------------------
  434. // CDocumentIterator::~CDocumentIterator: 
  435. //----------------------------------------------------------------------------------------
  436. #pragma segment IteratorRes
  437.  
  438. CDocumentIterator::~CDocumentIterator()
  439. {
  440. } // CDocumentIterator::~CDocumentIterator 
  441.  
  442. //----------------------------------------------------------------------------------------
  443. // CDocumentIterator::CurrentDocument: 
  444. //----------------------------------------------------------------------------------------
  445. #pragma segment MAApplicationRes
  446.  
  447. TDocument* CDocumentIterator::CurrentDocument()
  448. {
  449.     return (TDocument *)this->CurrentObject();
  450. } // CDocumentIterator::CurrentDocument 
  451.  
  452. //----------------------------------------------------------------------------------------
  453. // CDocumentIterator::FirstDocument: 
  454. //----------------------------------------------------------------------------------------
  455. #pragma segment MAApplicationRes
  456.  
  457. TDocument* CDocumentIterator::FirstDocument()
  458. {
  459.     return (TDocument *)this->FirstObject();
  460. } // CDocumentIterator::FirstDocument 
  461.  
  462. //----------------------------------------------------------------------------------------
  463. // CDocumentIterator::NextDocument: 
  464. //----------------------------------------------------------------------------------------
  465. #pragma segment MAApplicationRes
  466.  
  467. TDocument* CDocumentIterator::NextDocument()
  468. {
  469.     return (TDocument *)this->NextObject();
  470. } // CDocumentIterator::NextDocument 
  471.  
  472.  
  473. //========================================================================================
  474. // struct CSetupTheMenus
  475. //========================================================================================
  476.  
  477. struct CSetupTheMenus
  478. {
  479. public:
  480.     TApplication* fApplication;
  481.  
  482.     // Constructor
  483.     CSetupTheMenus(TApplication* theApplication) :
  484.         fApplication(theApplication)
  485.     {
  486.     }
  487. };
  488.  
  489. //----------------------------------------------------------------------------------------
  490. // DoSetupTheMenus: 
  491. //----------------------------------------------------------------------------------------
  492. #pragma segment MAApplicationRes
  493.  
  494. void DoSetupTheMenus(void* /* staticLink */)
  495. {
  496.     // Set the Undo menu to "Can't Undo" before giving the target chain a chance
  497.     // to change it.
  498.     gApplication->SetUndoText(kShowCantUndo, cCantUndo);
  499.  
  500.     gClipboardMgr->fGotClipType = false;          // so CanPaste will work correctly
  501.     gApplication->GetTarget()->HandleSetupMenus();// Setup menus relevant to target chain 
  502.  
  503.     // Set up the menu commands that are not dependent on the target chain… 
  504.  
  505.     if (gApplication->fSysWindowActive)
  506.     {
  507.         Enable(cUndo, true);
  508.         Enable(cCut, true);
  509.         Enable(cCopy, true);
  510.         Enable(cPaste, true);
  511.         Enable(cClear, true);
  512.  
  513.         gApplication->SetUndoText(kShowUndo, cNoCommand);
  514.     }
  515.  
  516. #if qDebug
  517.     {
  518.         TWindow * aWindow = gApplication->GetActiveWindow(kNoFloaters);
  519.  
  520.         Enable(cRefreshFrontWindow, (aWindow != NULL));
  521.         Enable(cDoFirstClick, (aWindow != NULL));
  522.         if (aWindow)
  523.             SetMenuState(cDoFirstClick, kDebugBuzzStrings, bzDoFirstClick, bzDontDoFirstClick, aWindow->fDoFirstClick);
  524.  
  525.         Enable(cDebugFlags, true);
  526.  
  527.         // System Justification - see comment in Debug.r
  528.     //    Enable(cSetSysJust, true);
  529.     //    SetMenuState(cSetSysJust, kDebugBuzzStrings, bzSetRightSysJust, bzSetLeftSysJust, GetSysDirection() != smSysJustLeft);
  530.     }
  531. #endif
  532.  
  533. #if qPerform
  534.     {
  535.         Boolean initiated = PerfMonitorInitiated();
  536.         
  537.         Enable(cPerfMonInit, !initiated);
  538.         Enable(cPerfMonDump, initiated);
  539.         Enable(cPerfMonToggle, initiated);
  540.         SetMenuState(cPerfMonToggle, kDebugBuzzStrings, bzContinuePerfMon, bzPausePerfMon, PerfMonitorEnabled());
  541.         Enable(cPerfMonEnd, initiated);
  542.     }
  543. #endif
  544.  
  545.     MenuHandle appleMenu = MAGetMenuHandle(mApple);
  546.     if (appleMenu != 0)
  547.     {
  548.         if (((*appleMenu)->enableFlags & 1) == gApplication->InModalState())
  549.         {
  550.             (*appleMenu)->enableFlags = ((*appleMenu)->enableFlags ^ 1);
  551.             InvalidateMenuBar();
  552.         }
  553.     }
  554.  
  555. } // DoSetupTheMenus 
  556.  
  557.  
  558. //========================================================================================
  559. // CLASS TEventList: Empty constructor to satisfy the compiler.
  560. //========================================================================================
  561. #undef Inherited
  562. #define Inherited TSortedList
  563.  
  564. #pragma segment MAInit
  565. DefineClass(TEventList, Inherited);
  566.  
  567. //----------------------------------------------------------------------------------------
  568. // TEventList::TEventList: Empty constructor to satisfy the compiler. 
  569. //----------------------------------------------------------------------------------------
  570. #pragma segment ConstructorRes
  571.  
  572. TEventList::TEventList()
  573. {
  574. } // TEventList::TEventList 
  575.  
  576. //----------------------------------------------------------------------------------------
  577. // TEventList::Compare: 
  578. //----------------------------------------------------------------------------------------
  579. #pragma segment MAApplicationRes
  580.  
  581. CompareResult TEventList::Compare(TObject* item1,
  582.                                   TObject* item2)
  583. {
  584.     // We want higher priority events at the end of the queue so we can delete from the
  585.     // end of the list. This will save us a block move in DeleteElementsAt.
  586.     if (((TEvent *)item1)->fPriority > ((TEvent *)item2)->fPriority)
  587.         return kItem1LessThanItem2;
  588.     else if (((TEvent *)item1)->fPriority < ((TEvent *)item2)->fPriority)
  589.         return kItem1GreaterThanItem2;
  590.     else
  591.         return kItem1EqualItem2;
  592. } // TEventList::Compare 
  593.  
  594. //----------------------------------------------------------------------------------------
  595. // TEventList::IEventList: 
  596. //----------------------------------------------------------------------------------------
  597. #pragma segment MAInit
  598.  
  599. void TEventList::IEventList()
  600. {
  601.     this->ISortedList();
  602. } // TEventList::IEventList 
  603.  
  604. //----------------------------------------------------------------------------------------
  605. // TEventList::Insert: 
  606. //----------------------------------------------------------------------------------------
  607. #pragma segment MAApplicationRes
  608.  
  609. void TEventList::Insert(TObject* item)    // override 
  610. {
  611.     // Guarantee that the insertion can take place. Use AllocateObjectsFromPerm rather
  612.     // than PermAllocation because TDynamicArray calls TObject::SetDynamicSize to change
  613.     // the size of the array. TObject::SetDynamicSize checks the object allocation flag to
  614.     // decide whether to use temporary or permanent memory for the resize.
  615.     
  616.     Boolean oldObjectPerm = AllocateObjectsFromPerm(false);
  617.     VOLATILE(oldObjectPerm);
  618.     
  619.     FailInfo fi;
  620.     Try(fi)
  621.     {
  622.         Inherited::Insert(item);
  623.         fi.Success();
  624.     }
  625.     else
  626.     {
  627.         AllocateObjectsFromPerm(oldObjectPerm);
  628.         fi.ReSignal();
  629.     }
  630.     
  631.     AllocateObjectsFromPerm(oldObjectPerm);
  632. } // TEventList::Insert 
  633.  
  634.  
  635. //========================================================================================
  636. // CLASS TQuitCommand
  637. //========================================================================================
  638. #undef Inherited
  639. #define Inherited TCommand
  640.  
  641. #pragma segment MAApplicationRes
  642. DefineClass(TQuitCommand, Inherited);
  643.  
  644. //----------------------------------------------------------------------------------------
  645. // TQuitCommand: Empty constructor to satisfy the compiler.
  646. //----------------------------------------------------------------------------------------
  647. #pragma segment ConstructorRes
  648.  
  649. TQuitCommand::TQuitCommand()
  650. {
  651. } // TQuitCommand::TQuitCommand
  652.  
  653. //----------------------------------------------------------------------------------------
  654. // TQuitCommand::DoIt: 
  655. //----------------------------------------------------------------------------------------
  656. #pragma segment MAApplicationRes
  657.  
  658. void TQuitCommand::DoIt()
  659. {
  660.     FailInfo fi;
  661.     Try(fi)
  662.     {
  663.         gApplication->fDone = true;
  664.         gApplication->Close();
  665.         fi.Success();
  666.     }
  667.     else                                        // Recover
  668.     {
  669.         gApplication->fDone = false;
  670.         fi.ReSignal();
  671.     }
  672. } // TQuitCommand::DoIt 
  673.  
  674. //----------------------------------------------------------------------------------------
  675. // TQuitCommand::IQuitCommand: 
  676. //----------------------------------------------------------------------------------------
  677. #pragma segment MASelCommand
  678.  
  679. void TQuitCommand::IQuitCommand(CommandNumber itsCommandNumber)
  680. {
  681.     this->ICommand(itsCommandNumber, gApplication, kCantUndo, kDoesNotCauseChange, NULL);
  682. } // TQuitCommand::IQuitCommand 
  683.  
  684. //----------------------------------------------------------------------------------------
  685. // TQuitCommand::IsReadyToExecute: 
  686. //----------------------------------------------------------------------------------------
  687. #pragma segment MAApplicationRes
  688.  
  689. Boolean TQuitCommand::IsReadyToExecute()    // Override
  690. {
  691.     // Don't execute Quit if application has a dialog posed modally!
  692.     if (gApplication->InModalState())
  693.         return false;
  694.     else
  695.         return fReadyToExecute;
  696. }
  697.  
  698. //========================================================================================
  699. // CLASS TNewDocumentCommand
  700. //========================================================================================
  701. #undef Inherited
  702. #define Inherited TCommand
  703.  
  704. #pragma segment MAOpen
  705. DefineClass(TNewDocumentCommand, Inherited);
  706.  
  707. //----------------------------------------------------------------------------------------
  708. // TNewDocumentCommand: Empty constructor to satisfy the compiler.
  709. //----------------------------------------------------------------------------------------
  710. #pragma segment ConstructorRes
  711.  
  712. TNewDocumentCommand::TNewDocumentCommand()
  713. {
  714. } // TNewDocumentCommand::TNewDocumentCommand
  715.  
  716. //----------------------------------------------------------------------------------------
  717. // TNewDocumentCommand::DoIt: 
  718. //----------------------------------------------------------------------------------------
  719. #pragma segment MAOpen
  720.  
  721. void TNewDocumentCommand::DoIt()
  722. {
  723.     gApplication->OpenNew(fIdentifier);
  724. } // TNewDocumentCommand::DoIt 
  725.  
  726. //----------------------------------------------------------------------------------------
  727. // TNewDocumentCommand::INewDocumentCommand: 
  728. //----------------------------------------------------------------------------------------
  729. #pragma segment MASelCommand
  730.  
  731. void TNewDocumentCommand::INewDocumentCommand(CommandNumber itsCommandNumber)
  732. {
  733.     this->ICommand(itsCommandNumber, gApplication, kCantUndo, kDoesNotCauseChange, NULL);
  734. } // TNewDocumentCommand::INewDocumentCommand 
  735.  
  736.  
  737. //========================================================================================
  738. // CLASS TFilesCommand
  739. //========================================================================================
  740. #undef Inherited
  741. #define Inherited TServerCommand
  742.  
  743. #pragma segment MASelCommand
  744. DefineClass(TFilesCommand, Inherited);
  745.  
  746. //----------------------------------------------------------------------------------------
  747. // TFilesCommand constructor
  748. //----------------------------------------------------------------------------------------
  749. #pragma segment MASelCommand
  750.  
  751. TFilesCommand::TFilesCommand()
  752. {
  753.     fCausesChange = false;
  754.     fFileList = NULL;
  755. } // TFilesCommand::TFilesCommand
  756.  
  757. //----------------------------------------------------------------------------------------
  758. // TFilesCommand::IFilesCommand: 
  759. //----------------------------------------------------------------------------------------
  760. #pragma segment MASelCommand
  761.  
  762. void TFilesCommand::IFilesCommand(CommandNumber itsCommandNumber,
  763.                                   TList* theDocuments)
  764. {
  765.     this->IServerCommand(itsCommandNumber, gApplication, kCantUndo, kDoesNotCauseChange, NULL);
  766.     fFileList = theDocuments;
  767. } // TFilesCommand::IFilesCommand 
  768.  
  769. //----------------------------------------------------------------------------------------
  770. // TFilesCommand::InitializeFromAppleEvent: 
  771. //----------------------------------------------------------------------------------------
  772. #pragma segment MASelCommand
  773.  
  774. void TFilesCommand::InitializeFromAppleEvent(CommandNumber itsCommandNumber,
  775.                                              TCommandHandler* itsContext,
  776.                                              Boolean canUndo,
  777.                                              Boolean causesChange,
  778.                                              TObject* objectToNotify,
  779.                                              const AppleEvent& itsMessage,
  780.                                              const AppleEvent& itsReply)    // override 
  781. {
  782.     Inherited::InitializeFromAppleEvent(itsCommandNumber, itsContext, canUndo, causesChange, objectToNotify, itsMessage, itsReply);
  783.  
  784.     THandleList * aHandleList = NULL;
  785.     TList * aFileList = NULL;
  786.  
  787.     VOLATILE(aHandleList);
  788.     VOLATILE(aFileList);
  789.     
  790.     FailInfo outerFi;
  791.     Try(outerFi)
  792.     {
  793.         aHandleList = new THandleList;
  794.         aHandleList->IHandleList();
  795.  
  796.         FailInfo innerfi;
  797.         Try(innerfi)
  798.         {
  799.             aFileList = NewList();
  800.     
  801.             fMessage->ReadHandleList(keyDirectObject, typeAlias, aHandleList);
  802.     
  803.             // Block is necessary for correct failure handling
  804.             {
  805.                 CHandleIterator iter(aHandleList);
  806.     
  807.                 for (Handle item = iter.FirstHandle(); iter.More(); item = iter.NextHandle())
  808.                 {
  809.                     TFile* aFile = NULL;
  810.                     VOLATILE(aFile);
  811.     
  812.                     aFile = gApplication->DoMakeFile(itsCommandNumber);
  813.  
  814.                     FailInfo onemorefi;
  815.                     Try(onemorefi)
  816.                     {
  817.                         FailOSErr(aFile->SpecifyWithAlias(AliasHandle(item)));
  818.                         aFileList->InsertLast(aFile);
  819.                         onemorefi.Success();
  820.                     }
  821.                     else
  822.                     {
  823.                         aFile = (TFile*)FreeIfObject(aFile);
  824.                         onemorefi.ReSignal();
  825.                     }
  826.                     
  827.                     aHandleList->Delete(item);        // Delete it from the list so if we fail
  828.                                                     // we don't try to free it twice
  829.                     item = DisposeIfHandle(item);
  830.                 }
  831.             }
  832.             innerfi.Success();
  833.         }
  834.         else                                        // Recover
  835.         {
  836.             if (aHandleList)
  837.                 aHandleList->FreeList();
  838.                 
  839.             if (aFileList)
  840.                 aFileList->FreeList();
  841.         
  842.             innerfi.ReSignal();
  843.         }
  844.         outerFi.Success();
  845.     }
  846.     else
  847.     {
  848.         this->Free();
  849.         outerFi.ReSignal();
  850.     }
  851.  
  852.     aHandleList->Free();                        // It is just a list of disposed handles…
  853.  
  854.     fFileList = aFileList;
  855. } // TFilesCommand::InitializeFromAppleEvent 
  856.  
  857. //----------------------------------------------------------------------------------------
  858. // TFilesCommand::Free: 
  859. //----------------------------------------------------------------------------------------
  860. #pragma segment MAClose
  861.  
  862. void TFilesCommand::Free()                // override 
  863. {
  864.     fFileList = (TList*)FreeListIfObject(fFileList);
  865.  
  866.     Inherited::Free();
  867. } // TFilesCommand::Free 
  868.  
  869.  
  870. //========================================================================================
  871. // CLASS TODocCommand
  872. //========================================================================================
  873. #undef Inherited
  874. #define Inherited TFilesCommand
  875.  
  876. #pragma segment MASelCommand
  877. DefineClass(TODocCommand, Inherited);
  878.  
  879. //----------------------------------------------------------------------------------------
  880. // TODocCommand: Empty constructor to satisfy the compiler.
  881. //----------------------------------------------------------------------------------------
  882. #pragma segment ConstructorRes
  883.  
  884. TODocCommand::TODocCommand()
  885. {
  886. } // TODocCommand::TODocCommand
  887.  
  888. //----------------------------------------------------------------------------------------
  889. // TODocCommand::IODocCommand: 
  890. //----------------------------------------------------------------------------------------
  891. #pragma segment MASelCommand
  892.  
  893. void TODocCommand::IODocCommand(CommandNumber itsCommandNumber,
  894.                                 TList* theDocuments)
  895. {
  896.     this->IFilesCommand(itsCommandNumber, theDocuments);
  897. } // TODocCommand::IODocCommand 
  898.  
  899. //----------------------------------------------------------------------------------------
  900. // TODocCommand::DoIt: 
  901. //----------------------------------------------------------------------------------------
  902. #pragma segment MAOpen
  903.  
  904. void TODocCommand::DoIt()                // override 
  905. {
  906.     FailInfo fi;
  907.     Try(fi)
  908.     {
  909.         gApplication->OpenOld(fIdentifier, fFileList);
  910.         fi.Success();
  911.     }
  912.     else
  913.     {
  914.         this->ReportError(fi.error, fi.message);
  915.         fi.ReSignal();
  916.     }
  917. } // TODocCommand::DoIt 
  918.  
  919.  
  920. //========================================================================================
  921. // CLASS TPDocCommand
  922. //========================================================================================
  923. #undef Inherited
  924. #define Inherited TFilesCommand
  925.  
  926. #pragma segment MASelCommand
  927. DefineClass(TPDocCommand, Inherited);
  928.  
  929. //----------------------------------------------------------------------------------------
  930. // TPDocCommand constructor
  931. //----------------------------------------------------------------------------------------
  932. #pragma segment MASelCommand
  933.  
  934. TPDocCommand::TPDocCommand()
  935. {
  936.     fRequiresUserInteraction = true;
  937. } // TPDocCommand::TPDocCommand
  938.  
  939. //----------------------------------------------------------------------------------------
  940. // TPDocCommand::IPDocCommand: 
  941. //----------------------------------------------------------------------------------------
  942. #pragma segment MASelCommand
  943.  
  944. void TPDocCommand::IPDocCommand(CommandNumber itsCommandNumber,
  945.                                 TList* theDocuments)
  946. {
  947.     this->IFilesCommand(itsCommandNumber, theDocuments);
  948. } // TPDocCommand::IPDocCommand 
  949.  
  950. //----------------------------------------------------------------------------------------
  951. // TPDocCommand::DoIt: 
  952. //----------------------------------------------------------------------------------------
  953. #pragma segment MAFinder
  954.  
  955. void TPDocCommand::DoIt()                // override 
  956. {
  957.     FailInfo fi;
  958.     Try(fi)
  959.     {
  960.         gApplication->PrintDocuments(fFileList);
  961.         fi.Success();
  962.     }
  963.     else
  964.     {
  965.         this->ReportError(fi.error, fi.message);
  966.         fi.ReSignal();
  967.     }
  968. } // TPDocCommand::DoIt 
  969.  
  970.  
  971. //========================================================================================
  972. // CLASS TAboutBoxCommand
  973. //========================================================================================
  974. #undef Inherited
  975. #define Inherited TCommand
  976.  
  977. #pragma segment MASelCommand
  978. DefineClass(TAboutBoxCommand, Inherited);
  979.  
  980. //----------------------------------------------------------------------------------------
  981. // TAboutBoxCommand: Empty constructor to satisfy the compiler.
  982. //----------------------------------------------------------------------------------------
  983. #pragma segment ConstructorRes
  984.  
  985. TAboutBoxCommand::TAboutBoxCommand()
  986. {
  987. }
  988.  
  989. //----------------------------------------------------------------------------------------
  990. // TAboutBoxCommand::IAboutBoxCommand: 
  991. //----------------------------------------------------------------------------------------
  992. #pragma segment MASelCommand
  993.  
  994. void TAboutBoxCommand::IAboutBoxCommand(CommandNumber itsCommandNumber)
  995. {
  996.     this->ICommand(itsCommandNumber, gApplication, kCantUndo, kDoesNotCauseChange, NULL);
  997. } // TAboutBoxCommand::IAboutBoxCommand 
  998.  
  999. //----------------------------------------------------------------------------------------
  1000. // TAboutBoxCommand::DoIt: 
  1001. //----------------------------------------------------------------------------------------
  1002. #pragma segment MAAboutApp
  1003.  
  1004. void TAboutBoxCommand::DoIt()
  1005. {
  1006.     gApplication->DoAboutBox();
  1007. } // TAboutBoxCommand::DoIt 
  1008.  
  1009.  
  1010. //========================================================================================
  1011. // CLASS TEventRetrieverCommand
  1012. //========================================================================================
  1013. #undef Inherited
  1014. #define Inherited TCommand
  1015.  
  1016. #pragma segment MASelCommand
  1017. DefineClass(TEventRetrieverCommand, Inherited);
  1018.  
  1019. //----------------------------------------------------------------------------------------
  1020. // TEventRetrieverCommand: Empty constructor to satisfy the compiler.
  1021. //----------------------------------------------------------------------------------------
  1022. #pragma segment ConstructorRes
  1023.  
  1024. TEventRetrieverCommand::TEventRetrieverCommand()
  1025. {
  1026. } // TEventRetrieverCommand::TEventRetrieverCommand
  1027.  
  1028. //----------------------------------------------------------------------------------------
  1029. // TEventRetrieverCommand::IEventRetrieverCommand: 
  1030. //----------------------------------------------------------------------------------------
  1031. #pragma segment MASelCommand
  1032.  
  1033. void TEventRetrieverCommand::IEventRetrieverCommand(CommandNumber itsCommandNumber)
  1034. {
  1035.     this->ICommand(itsCommandNumber, gApplication, kCantUndo, kDoesNotCauseChange, NULL);
  1036.  
  1037.     // Hang around 
  1038.     fFreeOnCompletion = false;
  1039.     fRecurring = true;
  1040.  
  1041.     // Let more important stuff happen first 
  1042.     fPriority = kPriorityLow;
  1043. } // TEventRetrieverCommand::IEventRetrieverCommand 
  1044.  
  1045. //----------------------------------------------------------------------------------------
  1046. // TEventRetrieverCommand::NeedsToUnloadAllSegments: 
  1047. //----------------------------------------------------------------------------------------
  1048. #pragma segment MAApplicationRes
  1049.  
  1050. Boolean TEventRetrieverCommand::NeedsToUnloadAllSegments()
  1051. {
  1052.     return false;
  1053. } // TEventRetrieverCommand::NeedsToUnloadAllSegments 
  1054.  
  1055. //----------------------------------------------------------------------------------------
  1056. // TEventRetrieverCommand::DoIt: 
  1057. //----------------------------------------------------------------------------------------
  1058. #pragma segment MAApplicationRes
  1059.  
  1060. void TEventRetrieverCommand::DoIt()
  1061. {
  1062.     gApplication->PollToolboxEvent(gApplication->fAllowApplicationToSleep);
  1063. } // TEventRetrieverCommand::DoIt 
  1064.  
  1065.  
  1066.  
  1067. #if qNeedsVU
  1068.  
  1069. //========================================================================================
  1070. // CLASS TVUApplication
  1071. //========================================================================================
  1072. #undef Inherited
  1073. #define Inherited TCommandHandler
  1074.  
  1075. #pragma segment MAInit
  1076. DefineClass(TVUApplication, Inherited);
  1077.  
  1078. //----------------------------------------------------------------------------------------
  1079. // TVUApplication constructor 
  1080. //----------------------------------------------------------------------------------------
  1081. #pragma segment MAInit
  1082.  
  1083. TVUApplication::TVUApplication()
  1084. {
  1085. } // TVUApplication::TVUApplication
  1086.  
  1087. //----------------------------------------------------------------------------------------
  1088. // TVUApplication::IVUApplication: 
  1089. //----------------------------------------------------------------------------------------
  1090. #pragma segment MAInit
  1091.  
  1092. void TVUApplication::IVUApplication()
  1093. {
  1094.     this->ICommandHandler(NULL);
  1095.  
  1096.     FailInfo fi;
  1097.     Try(fi)
  1098.     {
  1099.         gVUAssist = new TVUAssist();
  1100.         gVUAssist->IVUAssist(gUGridViewInitialized);
  1101.         fi.Success();
  1102.     }
  1103.     else
  1104.     {
  1105. #if qDebug
  1106.         ProgramBreak("Can't initialize the virtual user assist object!");
  1107. #endif
  1108.         this->Free();
  1109.         // we don't fail if we have no VU support
  1110.         gVUAssist = NULL;
  1111.     }
  1112.  
  1113. } // TVUApplication::IVUApplication
  1114.  
  1115.  
  1116. //----------------------------------------------------------------------------------------
  1117. // TVUApplication::Free: 
  1118. //----------------------------------------------------------------------------------------
  1119. #pragma segment MAClose
  1120.  
  1121. void TVUApplication::Free()                // override 
  1122. {
  1123.     gVUAssist = (TVUAssist*)FreeIfObject(gVUAssist);
  1124.  
  1125.     Inherited::Free();
  1126.     
  1127. } // TVUApplication::Free 
  1128.  
  1129. //----------------------------------------------------------------------------------------
  1130. // TVUApplication::AboutToLoseControl: 
  1131. //----------------------------------------------------------------------------------------
  1132. #pragma segment MAActivate
  1133.  
  1134. void TVUApplication::AboutToLoseControl(Boolean)
  1135. {
  1136.     if (gVUAssist) {
  1137.         gVUAssist->SuspendMole();
  1138.     }
  1139. } // TVUApplication::AboutToLoseControl 
  1140.  
  1141. //----------------------------------------------------------------------------------------
  1142. // TVUApplication::RegainControl: 
  1143. //----------------------------------------------------------------------------------------
  1144. #pragma segment MAApplicationRes
  1145.  
  1146. void TVUApplication::RegainControl(Boolean)
  1147. {
  1148.     if (gVUAssist) {
  1149.         gVUAssist->ResumeMole();
  1150.     }
  1151. } // TVUApplication::RegainControl 
  1152.  
  1153. #endif
  1154.  
  1155. //========================================================================================
  1156. // CLASS TApplication
  1157. //========================================================================================
  1158. #undef Inherited
  1159.  
  1160. #if qNeedsVU
  1161. #define Inherited TVUApplication
  1162. #else
  1163. #define Inherited TCommandHandler
  1164. #endif
  1165.  
  1166. #pragma segment MAInit
  1167. DefineClass(TApplication, Inherited);
  1168.  
  1169. //----------------------------------------------------------------------------------------
  1170. // TApplication constructor 
  1171. //----------------------------------------------------------------------------------------
  1172. #pragma segment MAInit
  1173.  
  1174. TApplication::TApplication()
  1175. {
  1176.     // This is a special case.  It needs to be available as soon as possible.
  1177.     gApplication = this;
  1178.  
  1179.     fMainFileType = 'TEXT';
  1180.     fCreator = '\?\?\?\?';
  1181.     fAllowApplicationToSleep = true;
  1182.     fAlwaysTrackCursor = false;
  1183.     fDone = false;
  1184.     fProcessNumber.highLongOfPSN = kNoProcess;
  1185.     fProcessNumber.lowLongOfPSN = kNoProcess;
  1186.     fClickCount = 0;
  1187.     fEventList = NULL;
  1188.     fPendingReplyList = NULL;
  1189.     fCursorRegion = NULL;
  1190.     fDocumentList = NULL;
  1191.     fEventLevel = 1;                        // Prevents UnloadAllSegs from getting called
  1192.                                             // if a modal dialogs is used befure starting
  1193.                                             // the main event loop
  1194.     fFreeWindowList = NULL;
  1195.     fHeadCohandler = NULL;
  1196.     fHelpRegion = NULL;
  1197.     fIdlePhase = idleEnd;
  1198.     fInBackground = false;                    // When we start an app, it's in foreground 
  1199.     fLastClickPart = inDesk;
  1200.     fLastMousePoint = gZeroPt;
  1201.     fLastUpTime = TickCount();
  1202.     fLaunchWithNewDocument = true;
  1203.     fLowSpaceInterval = kLowSpaceInterval;
  1204.     fMainEventMask = everyEvent;
  1205.     fDisplayedMenus = kMBarDisplayed;
  1206.     fOtherMenus = kMBarNotDisplayed;
  1207.     fMBarHierarchical = kMBarHierarchical;
  1208.     fNextSpaceMessage = TickCount();
  1209.     fSleepRegion = NULL;
  1210.     fSysWindowActive = false;
  1211.     fTarget = this;
  1212.     fUndoCommand = cNoCommand;
  1213.     fUndoState = kShowUndo;
  1214. #if qDebug
  1215.     fDebugFlagsWindow = NULL;
  1216. #endif
  1217. } // TApplication::TApplication 
  1218.  
  1219. //----------------------------------------------------------------------------------------
  1220. // TApplication::IApplication: 
  1221. //----------------------------------------------------------------------------------------
  1222. #pragma segment MAInit
  1223.  
  1224. void TApplication::IApplication(OSType itsMainFileType,
  1225.                                 OSType itsCreator)
  1226. {
  1227. #if qNeedsVU
  1228.     this->IVUApplication();
  1229. #else
  1230.     this->ICommandHandler(NULL);
  1231. #endif
  1232.  
  1233.     FailInfo fi;
  1234.     Try(fi)
  1235.     {
  1236.         fMainFileType = itsMainFileType;
  1237.         fCreator = itsCreator;
  1238.     
  1239.         fSleepRegion = MakeNewRgn();
  1240.         fCursorRegion = MakeNewRgn();
  1241.         fHelpRegion = MakeNewRgn();
  1242.     
  1243.         if (qNeedsProcessMgr || gConfiguration.hasProcessMgr)
  1244.             FailOSErr(GetCurrentProcess(&fProcessNumber));
  1245.     
  1246.         fFreeWindowList = NewList();
  1247. #if qDebug
  1248.         fFreeWindowList->SetEltType("TWindow");
  1249. #endif
  1250.     
  1251.         fDocumentList = NewList();
  1252. #if qDebug
  1253.         fDocumentList->SetEltType("TDocument");
  1254. #endif
  1255.     
  1256.         // Posted commands won't go anywhere until we create the queue 
  1257.         TEventList * anEventList = new TEventList;
  1258.         anEventList->IEventList();
  1259.         fEventList = anEventList;
  1260. #if qDebug
  1261.         fEventList->SetEltType("TEvent");
  1262. #endif
  1263.     
  1264.         anEventList = new TEventList;
  1265.         anEventList->IEventList();
  1266.         fPendingReplyList = anEventList;
  1267.     
  1268. #if qDebug
  1269.         fPendingReplyList->SetEltType("TClientCommand");
  1270. #endif
  1271.     
  1272.         // Allocate the global dependencyspace gMacAppDependencySpace
  1273.         this->DoMakeDependencySpace();
  1274.         
  1275.         // Make the command that operates the main Event Loop 
  1276.         TEventRetrieverCommand * aEventCommand = new TEventRetrieverCommand;
  1277.         aEventCommand->IEventRetrieverCommand(cNoCommand);
  1278.         this->PostCommand(aEventCommand);
  1279.     
  1280.         // Install the default tab  behavior 
  1281.         TMultiWindowTabber * aTabber = new TMultiWindowTabber;
  1282.         aTabber->IMultiWindowTabber(true);
  1283.         this->AddBehavior(aTabber);
  1284.     
  1285.         // Create the MenuBar manager object
  1286.         gMenuBarManager = this->MakeMenuBarManager();
  1287.     
  1288.         this->DoMakeViewServer();                    // creates the view server
  1289.  
  1290.         fi.Success();
  1291.     }
  1292.     else
  1293.     {
  1294. #if qDebug
  1295.         ProgramBreak("Can't initialize the application object!");
  1296. #endif
  1297.         this->Free();
  1298.         gApplication = NULL;
  1299.         fi.ReSignal();
  1300.     }
  1301. } // TApplication::IApplication 
  1302.  
  1303. //----------------------------------------------------------------------------------------
  1304. // TApplication::MakeMenuBarManager: 
  1305. //----------------------------------------------------------------------------------------
  1306. #pragma segment MAInit
  1307.  
  1308. // This function is called by IApplication to create the menu bar manager object.
  1309. TMenuBarManager* TApplication::MakeMenuBarManager()
  1310. {
  1311.     TMenuBarManager*    theMenuBarManager;
  1312.     
  1313.     theMenuBarManager = new TMenuBarManager;
  1314.     theMenuBarManager->IMenuBarManager( fOtherMenus );
  1315.     
  1316.     return theMenuBarManager;
  1317. } // TApplication::MakeMenuBarManager 
  1318.  
  1319. //----------------------------------------------------------------------------------------
  1320. // TApplication::AboutToLoseControl: 
  1321. //----------------------------------------------------------------------------------------
  1322. #pragma segment MAActivate
  1323.  
  1324. void TApplication::AboutToLoseControl(Boolean convertClipboard)
  1325. {
  1326. #if qNeedsVU
  1327.     Inherited::AboutToLoseControl(convertClipboard);
  1328. #endif
  1329.  
  1330.     gClipboardMgr->AboutToLoseControl(convertClipboard);
  1331.  
  1332.     // Let all windows know that we're losing control - e.g. so floaters can hide
  1333.     // themselves
  1334.     CWMgrIterator iter;
  1335.  
  1336.     for (WindowPtr aWinPtr = iter.FirstWMgrWindow(); iter.More(); aWinPtr = iter.NextWMgrWindow())
  1337.     {
  1338.         TWindow * aWindow = this->WMgrToWindow(aWinPtr);
  1339.         if (aWindow)
  1340.             aWindow->AboutToLoseControl();
  1341.     }
  1342.  
  1343.     this->ActivateBusyCursor(false);            // Don't want busy cursor while in DA
  1344.  
  1345. } // TApplication::AboutToLoseControl 
  1346.  
  1347.  
  1348. //----------------------------------------------------------------------------------------
  1349. // TApplication::ActivateBusyCursor: 
  1350. //----------------------------------------------------------------------------------------
  1351. #pragma segment MAApplicationRes
  1352.  
  1353. void TApplication::ActivateBusyCursor(Boolean entering)
  1354. {
  1355.     if (gBusyCursor)
  1356.         gBusyCursor->Activate(entering);
  1357. } // TApplication::ActivateBusyCursor 
  1358.  
  1359. //----------------------------------------------------------------------------------------
  1360. // TApplication::AddDocument: 
  1361. //----------------------------------------------------------------------------------------
  1362. #pragma segment MAOpen
  1363.  
  1364. void TApplication::AddDocument(TDocument* aNewDocument)
  1365. {
  1366.     if (fDocumentList)
  1367.         fDocumentList->Insert(aNewDocument);
  1368. } // TApplication::AddDocument 
  1369.  
  1370. //----------------------------------------------------------------------------------------
  1371. // TApplication::AddWindow: 
  1372. //----------------------------------------------------------------------------------------
  1373. #pragma segment MAOpen
  1374.  
  1375. void TApplication::AddWindow(TWindow* aWindow)
  1376. {
  1377.     // Protect against double installation
  1378.     if (fFreeWindowList && (fFreeWindowList->GetIdentityItemNo(aWindow) == 0))
  1379.         fFreeWindowList->Insert(aWindow);
  1380. } // TApplication::AddWindow 
  1381.  
  1382. //----------------------------------------------------------------------------------------
  1383. // TApplication::AlertFilter: AlertFilter is a default filterProc used by MacAppAlert if
  1384. // the filterProc passed in is NULL. It maps key strokes to the first character of button
  1385. // item titles. It also hands off activate and update processing to gApplication if we're
  1386. // not being called from an error condition or while nested.
  1387. //----------------------------------------------------------------------------------------
  1388. #pragma segment MAGlobalsRes
  1389. // Don't require a segment load for this 
  1390.  
  1391. Boolean TApplication::AlertFilter(DialogPtr theDialog,
  1392.                                   EventRecord& theEvent,
  1393.                                   short& itemHit)
  1394.  
  1395. {
  1396.     static CStr31 bufferString;                    // Must be a global, since it's used each
  1397.                                                 // time the alert filter is entered. (It
  1398.                                                 // could be a field of TApplication...) If
  1399.                                                 // any script has a character with more
  1400.                                                 // than 31 bytes then the creatures that
  1401.                                                 // speak that language have too many
  1402.                                                 // fingers!
  1403.  
  1404.     CRect box;
  1405.     short byteType;
  1406.     EventRecord anEvent;
  1407.     TToolboxEvent * event;
  1408.     Boolean oldObjectPerm;
  1409.     Boolean oldInFilterState = gInFilter;
  1410.     Boolean returnValue = false;
  1411.  
  1412.     VOLATILE(oldInFilterState);
  1413.     VOLATILE(returnValue);
  1414.  
  1415.     gInFilter = true;
  1416.     
  1417.     // First call the minimal alert filter; if it does not handle the
  1418.     // event, do some more complex handling
  1419.     returnValue = MinimalAlertFilter(theDialog, theEvent, itemHit);
  1420.     if( returnValue == false )
  1421.     {
  1422.         FailInfo fi;
  1423.         Try(fi)
  1424.         {
  1425.             // Wouldn't want MacApp to get lied to about where the focus _Actually_ is 
  1426.             if (!gInhibitNestedHandling &&!oldInFilterState)
  1427.                 this->InvalidateFocus();
  1428.     
  1429.             switch (theEvent.what)
  1430.             {
  1431.                 // this is the first event the alert gets, use it to initialize the global buffer
  1432.                 case activateEvt:
  1433.                     if (((DialogPtr)theEvent.message) == theDialog)
  1434.                         bufferString = gEmptyString;            // initialize bufferString
  1435.                     else if (!gInhibitNestedHandling &&!oldInFilterState)
  1436.                     {
  1437.                         GrafPtr savePort;
  1438.                         GetPort(&savePort);
  1439.                         
  1440.                         oldObjectPerm = AllocateObjectsFromPerm(false);
  1441.                         event = new TToolboxEvent;
  1442.                         AllocateObjectsFromPerm(oldObjectPerm);
  1443.                         event->IToolboxEvent(this, theEvent);
  1444.                         event->Process();
  1445.                         
  1446.                         SetPort(savePort);
  1447.                     }
  1448.                     break;
  1449.     
  1450.                 // this is the first event the alert gets, so let's determine our VARs
  1451.                 case updateEvt:
  1452.                     if (((DialogPtr)theEvent.message) != theDialog)
  1453.                         if (!gInhibitNestedHandling &&!oldInFilterState)
  1454.                         {
  1455.                             GrafPtr savePort;
  1456.                             GetPort(&savePort);
  1457.                             
  1458.                             oldObjectPerm = AllocateObjectsFromPerm(false);
  1459.                             event = new TToolboxEvent;
  1460.                             AllocateObjectsFromPerm(oldObjectPerm);
  1461.                             event->IToolboxEvent(this, theEvent);
  1462.                             event->Process();
  1463.                             
  1464.                             SetPort(savePort);
  1465.                         }
  1466.                     break;
  1467.     
  1468.                 // let's determine if the key pressed corresponds to our button titles
  1469.                 case keyDown:
  1470.                     oldObjectPerm = AllocateObjectsFromPerm(false);
  1471.                     event = new TToolboxEvent;
  1472.                     AllocateObjectsFromPerm(oldObjectPerm);
  1473.                     event->IToolboxEvent(this, theEvent);
  1474.                     
  1475.                     this->GetTarget()->KeyEventToComponents(event);// Find out what keys were _REALLY_ pressed
  1476.                     
  1477.                     bufferString += event->fCharacter;
  1478.                     event = (TToolboxEvent*)FreeIfObject(event);
  1479.                     
  1480.                     byteType = CharByte((Ptr)(&bufferString[1]), bufferString.Length() - 1);
  1481.     
  1482.                     switch (byteType)
  1483.                     {
  1484.                         case smSingleByte:
  1485.                             if (CompareAlertKeysToItem(theDialog, bufferString, itemHit))
  1486.                             {
  1487.                                 DoAlertKeyDown(theDialog, itemHit);
  1488.                                 returnValue = true;
  1489.                             }
  1490.                             bufferString = gEmptyString;                    // Clear the buffer for the next time around.
  1491.                             break;
  1492.     
  1493.                         case smFirstByte:
  1494.                         case smMiddleByte:
  1495.                             break;
  1496.     
  1497.                         case smLastByte:
  1498.                             if (CompareAlertKeysToItem(theDialog, bufferString, itemHit))
  1499.                             {
  1500.                                 DoAlertKeyDown(theDialog, itemHit);
  1501.                                 returnValue = true;
  1502.                             }
  1503.                             bufferString = gEmptyString;                    // Clear the buffer for the next time around.
  1504.                             break;
  1505.                     }
  1506.             }
  1507.     
  1508.             // Idle but only if _REALLY_ necessary 
  1509.             if (!gInhibitNestedHandling &&!oldInFilterState &&!EventAvail(everyEvent, &anEvent))
  1510.                 this->Idle(fIdlePhase);
  1511.     
  1512.             fi.Success();
  1513.         }
  1514.     }
  1515.     gInFilter = oldInFilterState;
  1516.  
  1517.     return returnValue;
  1518. } // TApplication::AlertFilter 
  1519.  
  1520. //----------------------------------------------------------------------------------------
  1521. // TApplication::AppleEventIdleProc: 
  1522. //----------------------------------------------------------------------------------------
  1523. #pragma segment MAGlobalsRes
  1524. // Don't require a segment load for this 
  1525.  
  1526. Boolean TApplication::AppleEventIdleProc(EventRecord& theEventRecord,
  1527.                                          long&/* sleepTime */ ,
  1528.                                          RgnHandle&/* mouseRgn */ )
  1529. {
  1530.     if ((theEventRecord.what == activateEvt) || (theEventRecord.what == updateEvt))
  1531.     {
  1532.         Boolean oldObjectPerm = AllocateObjectsFromPerm(false);
  1533.         TToolboxEvent* event = new TToolboxEvent;
  1534.         AllocateObjectsFromPerm(oldObjectPerm);
  1535.         event->IToolboxEvent(this, theEventRecord);
  1536.         event->Process();
  1537.     }
  1538.     return false;
  1539. } // TApplication::AppleEventIdleProc 
  1540.  
  1541. //----------------------------------------------------------------------------------------
  1542. // TApplication::StandardFileFilter: 
  1543. //----------------------------------------------------------------------------------------
  1544. #pragma segment MAGlobalsRes
  1545. // Don't require a segment load for this 
  1546.  
  1547. Boolean TApplication::StandardFileFilter(DialogPtr/* theDialog */,
  1548.                                          EventRecord& theEvent,
  1549.                                          short&/* itemHit */ ,
  1550.                                          void*/* yourDataPtr*/ )
  1551. {
  1552.     this->InvalidateFocus();
  1553.     switch (theEvent.what)
  1554.     {
  1555.         case activateEvt:
  1556.         case updateEvt:
  1557.             // check if intended for a MacApp window
  1558.             if (!this->WMgrToWindow((WindowPtr)theEvent.message))
  1559.                 break;
  1560.             // drop thru to processing the event
  1561.         case osEvt:
  1562.         case kHighLevelEvent:
  1563.             {
  1564.                 GrafPtr savePort;
  1565.                 
  1566.                 GetPort(&savePort);                // If the port get changed behind us
  1567.                                                 // the dialog can't find its controls
  1568.                 
  1569.                 Boolean oldObjectPerm = AllocateObjectsFromPerm(false);
  1570.                 TToolboxEvent* event = new TToolboxEvent;
  1571.                 AllocateObjectsFromPerm(oldObjectPerm);
  1572.                 event->IToolboxEvent(NULL, theEvent);
  1573.                 ++fEventLevel;
  1574.                 event->Process();
  1575.                 --fEventLevel;
  1576.                 
  1577.                 SetPort(savePort);
  1578.             }
  1579.             break;
  1580.     }
  1581.  
  1582.     return false;                                // did not take the event
  1583. } // TApplication::StandardFileFilter 
  1584.  
  1585. //----------------------------------------------------------------------------------------
  1586. // TApplication::FindDocument: 
  1587. //----------------------------------------------------------------------------------------
  1588. #pragma segment MAFile
  1589.  
  1590. TDocument* TApplication::FindDocument(TFile* aFile)
  1591. {
  1592.     CDocumentIterator iter(this);
  1593.  
  1594.     for (TDocument * aDocument = iter.FirstDocument(); iter.More(); aDocument = iter.NextDocument())
  1595.         if (aDocument->FindDocument(aFile))
  1596.             return aDocument;
  1597.     return NULL;                                // No document already open
  1598. } // TApplication::FindDocument 
  1599.  
  1600. //----------------------------------------------------------------------------------------
  1601. // TApplication::Beep: 
  1602. //----------------------------------------------------------------------------------------
  1603. #pragma segment MAApplicationRes
  1604.  
  1605. void TApplication::Beep(short duration)
  1606. {
  1607.     SysBeep(duration);
  1608. } // TApplication::Beep 
  1609.  
  1610. //----------------------------------------------------------------------------------------
  1611. // TApplication::CanOpenDocument: 
  1612. //----------------------------------------------------------------------------------------
  1613. #pragma segment MAFinder
  1614.  
  1615. // This is called only when opening/printing from the finder and from standard file;
  1616. // it simulates the filtering done by Std File.
  1617.  
  1618. Boolean TApplication::CanOpenDocument(CommandNumber itsCommandNumber,
  1619.                                       TFile* aFile)
  1620. {
  1621.     short dlgID;
  1622.     CPoint where;
  1623.     ProcPtr fileFilter;
  1624.     ProcPtr dlgHook;
  1625.     ProcPtr modalFilter;
  1626.     ProcPtr activateProc;
  1627.     Ptr activeList;
  1628.     void *yourDataPtr = NULL;
  1629.     TypeListHandle typeList;
  1630.  
  1631.     CInfoPBRec paramBlock;
  1632.     Boolean returnValue = false;
  1633.     CStr63 fileName;
  1634.  
  1635.     this->GetStandardFileParameters(itsCommandNumber, fileFilter, typeList, dlgID, where, dlgHook, modalFilter, activeList, activateProc, yourDataPtr);
  1636.  
  1637.     aFile->GetName(fileName);
  1638.  
  1639.     short numTypes = (short)(GetHandleSize((Handle)typeList) / sizeof(ResType));
  1640.  
  1641.     if (numTypes == 0)
  1642.     {
  1643.         if (!fileFilter)
  1644.             returnValue = true;                    // no file filter then want all types
  1645.         else if (aFile->GetCatInfo(paramBlock) == noErr)
  1646.         {
  1647.             paramBlock.hFileInfo.ioNamePtr = (StringPtr)fileName;
  1648.             // Call through the supplied filterProc
  1649.             if (qNeedsAliasMgr || gConfiguration.hasAliasMgr)
  1650.                 returnValue =!((FileFilterYDProcPtr)fileFilter)((ParamBlockRec*)¶mBlock, NULL);
  1651.             else
  1652.                 returnValue =!((FileFilterProcPtr)fileFilter)((ParamBlockRec*)¶mBlock);
  1653.         }
  1654.         else
  1655.             returnValue = false;
  1656.     }
  1657.     else
  1658.         for (short i = 0; i < numTypes; ++i)
  1659.             if (((long)(aFile->fFileType)) == ((long)(*typeList)[i]))
  1660.             {
  1661.                 if (!fileFilter)
  1662.                     returnValue = true;
  1663.                 else if (aFile->GetCatInfo(paramBlock) == noErr)
  1664.                 {
  1665.                     paramBlock.hFileInfo.ioNamePtr = (StringPtr)fileName;
  1666.                     // Call through the supplied filterProc
  1667.                     if (qNeedsAliasMgr || gConfiguration.hasAliasMgr)
  1668.                         returnValue =!((FileFilterYDProcPtr)fileFilter)((ParamBlockRec*)¶mBlock, NULL);
  1669.                     else
  1670.                         returnValue =!((FileFilterProcPtr)fileFilter)((ParamBlockRec*)¶mBlock);
  1671.                 }
  1672.                 else
  1673.                     returnValue = false;
  1674.                 break;
  1675.             }
  1676.  
  1677.     typeList = (TypeListHandle)DisposeIfHandle((Handle)typeList);
  1678.     return returnValue;
  1679. } // TApplication::CanOpenDocument 
  1680.  
  1681. //----------------------------------------------------------------------------------------
  1682. // TApplication::ChooseApplication: 
  1683. //----------------------------------------------------------------------------------------
  1684. #pragma segment MAOpen
  1685.  
  1686. Boolean TApplication::ChooseApplication(AEAddressDesc& theAddress)
  1687. {
  1688.     //    typedef TargetID* TargetIDPtr,
  1689.     //    ** TargetIDHdl;
  1690.  
  1691.     TargetIDHdl theTargetID;
  1692.     LocationNameRec theLoc;
  1693.     PortInfoRec thePortInfo;
  1694.     OSErr theErr;
  1695.     CStr32 theLocNBPType;
  1696.     Boolean returnValue = false;
  1697.  
  1698.     if (qNeedsAppleEventMgr || gConfiguration.hasAppleEventMgr)
  1699.     {
  1700.         theErr = PPCBrowser(gEmptyString, gEmptyString, false, &theLoc, &thePortInfo, NULL, gEmptyString);
  1701.         if (theErr == noErr)
  1702.         {
  1703.             theTargetID = (TargetIDHdl) NewPermHandle(sizeof(TargetID));
  1704.  
  1705.             (*theTargetID)->location = theLoc;
  1706.             (*theTargetID)->name = thePortInfo.name;
  1707.             theAddress.descriptorType = typeTargetID;
  1708.             theAddress.dataHandle = (Handle)theTargetID;
  1709.             returnValue = true;
  1710.         }
  1711.         else if (theErr != userCanceledErr)
  1712.             FailOSErr(theErr);
  1713.     }
  1714.     return returnValue;
  1715. } // TApplication::ChooseApplication 
  1716.  
  1717. //----------------------------------------------------------------------------------------
  1718. // TApplication::ChooseDocument: 
  1719. //----------------------------------------------------------------------------------------
  1720. #pragma segment MAOpen
  1721.  
  1722. Boolean TApplication::ChooseDocument(CommandNumber itsCommandNumber,
  1723.                                      TList** aFileList)
  1724. {
  1725.     typedef SFTypeList* SFTypeListPtr;
  1726.     typedef SFTypeListPtr* SFTypeListHandle;
  1727.  
  1728.     short dlgID;
  1729.     CPoint where;
  1730.     ProcPtr fileFilter;
  1731.     ProcPtr dlgHook;
  1732.     ProcPtr modalFilter;
  1733.     ProcPtr activateProc;
  1734.     Ptr activeList;
  1735.     void* yourDataPtr = NULL;
  1736.     TypeListHandle typeList;
  1737.     SFTypeListPtr pTypeList;
  1738.     short numTypes;
  1739.     Boolean fileChosen;
  1740.  
  1741.     TFile * aFile = NULL;
  1742.  
  1743.     VOLATILE(aFileList);
  1744.     VOLATILE(aFile);
  1745.  
  1746.     this->GetStandardFileParameters(itsCommandNumber, fileFilter, typeList, dlgID, where, dlgHook, modalFilter, activeList, activateProc, yourDataPtr);
  1747.  
  1748.     numTypes = (short)(GetHandleSize((Handle)typeList) / sizeof(ResType));
  1749.  
  1750.     if (numTypes == 0)
  1751.     {
  1752.         numTypes = -1;                            // Tell Std File to display all types.
  1753.         pTypeList = (SFTypeListPtr) & pTypeList;// arbitrary, as long as it points to 4 bytes of valid memory
  1754.     }
  1755.     else
  1756.     {
  1757.         LockHandleHigh((Handle)typeList);        // in case Std File does allocations 
  1758.         pTypeList = *((SFTypeListHandle)typeList);
  1759.     }
  1760.  
  1761. #if qDebug
  1762.     // Causes TApplication::GetEvent to call CheckRsrcUsage. 
  1763.     gRsrcCheck = 0;
  1764. #endif
  1765.  
  1766.     FailInfo fi;
  1767.     Try(fi)
  1768.     {
  1769.  
  1770.         aFile = this->DoMakeFile(itsCommandNumber);
  1771.         fileChosen = false;
  1772.  
  1773.         FailOSErr(MAInteractWithUser(kNoTimeOut, gNotificationPtr, gMacAppAppleEventIdleProc)); 
  1774.  
  1775.         if (yourDataPtr == NULL) {
  1776.             yourDataPtr = &itsCommandNumber;
  1777.         }
  1778.         
  1779. #if !qPowerPC
  1780.         if (gConfiguration.hasCustomFile)
  1781.         {
  1782. #endif
  1783.             StandardFileReply customReply;
  1784.  
  1785.             gClipboardMgr->AboutToLoseControl(true);            // so scrap gets converted
  1786.             
  1787.             FileFilterYDUPP cgfFileFilter = NewFileFilterYDProc(fileFilter);
  1788.             DlgHookYDUPP cgfDlgHook = NewDlgHookYDProc(dlgHook);
  1789.             ModalFilterYDUPP cgfModalFilter = NewModalFilterYDProc(modalFilter);
  1790.             ActivateYDUPP cgfActivateProc = NewActivateYDProc(activateProc);
  1791.  
  1792.             CustomGetFile(cgfFileFilter, numTypes, (*pTypeList), &customReply, dlgID, where, cgfDlgHook, cgfModalFilter, (short*)activeList, cgfActivateProc, yourDataPtr);
  1793.             
  1794.             cgfFileFilter = (FileFilterYDUPP)DisposeIfRoutineDescriptor((UniversalProcPtr)cgfFileFilter);
  1795.             cgfDlgHook = (DlgHookYDUPP)DisposeIfRoutineDescriptor((UniversalProcPtr)cgfDlgHook);
  1796.             cgfModalFilter = (ModalFilterYDUPP)DisposeIfRoutineDescriptor((UniversalProcPtr)cgfModalFilter);
  1797.             cgfActivateProc = (ActivateYDUPP)DisposeIfRoutineDescriptor((UniversalProcPtr)cgfActivateProc);
  1798.             
  1799.             gClipboardMgr->RegainControl(true);            // so scrap gets converted
  1800.  
  1801.             fileChosen = customReply.sfGood;
  1802.             if (fileChosen)
  1803.                 aFile->SpecifyWithStandardFileReply(customReply);
  1804. #if !qPowerPC
  1805.         // the following block of code is the "else" block for the above Gestalt check - 
  1806.         // as with that check, it is only relevant if we are not built for PowerPC
  1807.         }
  1808.         else
  1809.         {
  1810.             SFReply reply;
  1811.  
  1812.             // We will pass the address of the CallBack instead of the modalFilter to
  1813.             // SFPGetFile It will add yourDataPtr parameter before passing on to the
  1814.             // ModalFilterProc supplied by SFPutParms this lets us assume a single calling
  1815.             // convention for that function.
  1816.  
  1817.             // Don't create a CallBack when the SF callback is NULL.
  1818.             // Also, pass itsCommandNumber as a default yourDataPtr.
  1819.             
  1820.             CallBack myFileFilterCallBack;
  1821.             SetCallBack(fileFilter, (long)yourDataPtr, &myFileFilterCallBack);
  1822.             FileFilterProcPtr aFileFilterProcPtr = fileFilter ? (FileFilterProcPtr)&myFileFilterCallBack : NULL;
  1823.  
  1824.             CallBack myModalHookCallBack;
  1825.             SetCallBack(dlgHook, (long)yourDataPtr, &myModalHookCallBack);
  1826.             DlgHookProcPtr aDlgHookProcPtr = dlgHook ? (DlgHookProcPtr)&myModalHookCallBack : NULL;
  1827.     
  1828.             CallBack myModalFilterCallBack;
  1829.             SetCallBack(modalFilter, (long)yourDataPtr, &myModalFilterCallBack);
  1830.             ModalFilterProcPtr aModalFilterProcPtr = modalFilter ? (ModalFilterProcPtr)&myModalFilterCallBack : NULL;
  1831.  
  1832.             gClipboardMgr->AboutToLoseControl(true);    // so scrap gets converted
  1833.  
  1834.             SFPGetFile(where, gEmptyString, aFileFilterProcPtr, numTypes, (*pTypeList), aDlgHookProcPtr, &reply, dlgID, aModalFilterProcPtr);
  1835.             
  1836.             gClipboardMgr->RegainControl(true);            // so scrap gets converted
  1837.  
  1838.             fileChosen = reply.good;
  1839.             if (fileChosen)
  1840.                 FailOSErr(aFile->SpecifyWithSFReply(reply));
  1841.         }
  1842. #endif
  1843.         fi.Success();
  1844.     }
  1845.     else                                        // Recover
  1846.     {
  1847.         typeList = (TypeListHandle)DisposeIfHandle((Handle)typeList);
  1848.         aFile = (TFile *)FreeIfObject(aFile);
  1849.         fi.ReSignal();
  1850.     }
  1851.  
  1852.     typeList = (TypeListHandle)DisposeIfHandle((Handle)typeList);
  1853.  
  1854.     if (fileChosen)
  1855.     {
  1856.         FailInfo fi;
  1857.         Try(fi)
  1858.         {
  1859.             // Return the file(s) chosen 
  1860.             *aFileList = NewList();
  1861.             (*aFileList)->InsertLast(aFile);
  1862.             fi.Success();
  1863.         }
  1864.         else
  1865.         {
  1866.             if (*aFileList)
  1867.                 *aFileList = (TList*)FreeIfObject(*aFileList);
  1868.             aFile = (TFile*)FreeIfObject(aFile);
  1869.             fi.ReSignal();
  1870.         }
  1871.     }
  1872.     else                                        // user cancelled or something 
  1873.         aFile = (TFile *)(FreeIfObject(aFile));    // free the unwanted file object 
  1874.     return fileChosen;
  1875. } // TApplication::ChooseDocument 
  1876.  
  1877. //----------------------------------------------------------------------------------------
  1878. // TApplication::Close: 
  1879. //----------------------------------------------------------------------------------------
  1880. #pragma segment MATerminate
  1881.  
  1882. void TApplication::Close()
  1883. {
  1884.     // Close all of the visible non-floater windows 
  1885.     WindowPtr aWMgrWindow;
  1886.  
  1887.     while ((aWMgrWindow = MAFrontWindow()) != NULL)
  1888.         this->CloseToolboxWindow(aWMgrWindow);
  1889.  
  1890.     // Close all of the windows 
  1891.     while ((aWMgrWindow = FrontWindow()) != NULL)
  1892.         this->CloseToolboxWindow(aWMgrWindow);
  1893.  
  1894.     // Close any windowless documents.  Add a block for failure handling
  1895.     {
  1896.         CDocumentIterator iter(this);
  1897.         TDocument * clipDocument = NULL;
  1898.         if (gClipboardMgr->fClipView)
  1899.             clipDocument = gClipboardMgr->fClipView->fDocument;
  1900.  
  1901.         for (TDocument * aDocument = iter.FirstDocument(); iter.More(); aDocument = iter.NextDocument())
  1902.             if (!clipDocument || aDocument != clipDocument)
  1903.                 aDocument->CloseAndFree();
  1904.     }
  1905.  
  1906.     // Close down the cohandler chain.  Add a block for failure handling
  1907.     {
  1908.         CHandlerIterator iter(fHeadCohandler);
  1909.  
  1910.         for (TEventHandler * aHandler = iter.FirstHandler(); iter.More(); aHandler = iter.NextHandler())
  1911.             FreeIfObject(aHandler);
  1912.     }
  1913.  
  1914.     gClipboardMgr->Close();
  1915.  
  1916.     gViewServer = (TViewServer *)FreeIfObject(gViewServer); // won't be creating any more views...
  1917.     
  1918. } // TApplication::Close 
  1919.  
  1920. //----------------------------------------------------------------------------------------
  1921. // TApplication::CloseToolboxWindow: 
  1922. //----------------------------------------------------------------------------------------
  1923. #pragma segment MAClose
  1924.  
  1925. void TApplication::CloseToolboxWindow(WindowPtr aWMgrWindow)
  1926. {
  1927.     TWindow * aWindow;
  1928.  
  1929.     if (qNeedsProcessMgr || gConfiguration.hasProcessMgr ||!IsDeskAccessory(aWMgrWindow))
  1930.     {
  1931.         aWindow = this->WMgrToWindow(aWMgrWindow);
  1932.         if (aWindow)
  1933.             aWindow->CloseByUser();
  1934.         else
  1935.             HideWindow(aWMgrWindow);
  1936.     }
  1937.     else
  1938.         CloseDeskAcc(((WindowPeek)aWMgrWindow)->windowKind);
  1939. } // TApplication::CloseToolboxWindow 
  1940.  
  1941. //----------------------------------------------------------------------------------------
  1942. // TApplication::CountClicks: 
  1943. //----------------------------------------------------------------------------------------
  1944. #pragma segment MAApplicationRes
  1945.  
  1946. short TApplication::CountClicks(TToolboxEvent* event,
  1947.                                 short whereMouseDown)
  1948. {
  1949.     short newClickCount;
  1950.  
  1951.     newClickCount = 1;
  1952.  
  1953.     if ((whereMouseDown == fLastClickPart) &&    // clicked in the same place… 
  1954.         (fClickCount > 0) &&                    // not the first click… 
  1955.         (event->fEventRecord.when - fLastUpTime < GetDblTime()) &&// close enough in time… 
  1956.         this->GetTarget()->DoMultiClick(fLastMousePoint, event->fEventRecord.where))// close enough in space
  1957.         newClickCount = fClickCount + 1;
  1958.  
  1959.     fLastMousePoint = event->fEventRecord.where;
  1960.  
  1961.     fLastClickPart = whereMouseDown;
  1962.     fClickCount = newClickCount;
  1963.     return newClickCount;
  1964. } // TApplication::CountClicks 
  1965.  
  1966. //----------------------------------------------------------------------------------------
  1967. // TApplication::DeleteDocument: 
  1968. //----------------------------------------------------------------------------------------
  1969. #pragma segment MAClose
  1970.  
  1971. void TApplication::DeleteDocument(TDocument* docToDelete)
  1972. {
  1973.     if (fDocumentList)
  1974.         fDocumentList->Delete(docToDelete);
  1975. } // TApplication::DeleteDocument 
  1976.  
  1977. //----------------------------------------------------------------------------------------
  1978. // TApplication::DeleteWindow: 
  1979. //----------------------------------------------------------------------------------------
  1980. #pragma segment MAApplicationRes
  1981.  
  1982. void TApplication::DeleteWindow(TWindow* windowToDelete)
  1983. {
  1984.     if (fFreeWindowList)
  1985.         fFreeWindowList->Delete(windowToDelete);
  1986. } // TApplication::DeleteWindow 
  1987.  
  1988. //----------------------------------------------------------------------------------------
  1989. // TApplication::DispatchEvent: 
  1990. //----------------------------------------------------------------------------------------
  1991. #pragma segment MAApplicationRes
  1992.  
  1993. void TApplication::DispatchEvent(TToolboxEvent* event)
  1994. {
  1995.     // For Toolbox events, fIdentifier == fEventRecord.what 
  1996.     if (event)
  1997.     {
  1998.         switch (event->fIdentifier)
  1999.         {
  2000.             case mouseUp:
  2001.                 this->HandleMouseUp(event);
  2002.                 break;
  2003.  
  2004.             case mouseDown:
  2005.                 this->HandleMouseDown(event);
  2006.                 break;
  2007.  
  2008.             case activateEvt:
  2009.                 this->HandleActivateEvent(event);
  2010.                 break;
  2011.  
  2012.             case updateEvt:
  2013.                 this->HandleUpdateEvent(event);
  2014.                 break;
  2015.  
  2016.             case keyDown:
  2017.             case autoKey:
  2018.                 this->HandleKeyDownEvent(event);
  2019.                 break;
  2020.  
  2021.             case keyUp:
  2022.                 // A MultiFinder™ bug (at least up to 6.0) keep us from reliably getting
  2023.                 // keyUp events after minor context switches (background updates, etc.).
  2024.                 // It replaces the global event mask (which we would have had to change to
  2025.                 // get keyups in the first place) with the wrong mask. Fixed in system 7.0
  2026.  
  2027.                 this->HandleKeyUpEvent(event);
  2028.                 break;
  2029.  
  2030.             case diskEvt:
  2031.                 this->HandleDiskEvent(event);
  2032.                 break;
  2033.  
  2034.             case osEvt:
  2035.                 this->HandleSystemEvent(event);
  2036.                 break;
  2037.  
  2038.             case nullEvent:
  2039.             case networkEvt:
  2040.             case driverEvt:
  2041.             case app1Evt:
  2042.             case app2Evt:
  2043.             case app3Evt:
  2044.                 this->HandleAlienEvent(event);
  2045.                 break;
  2046.  
  2047.             case kHighLevelEvent:
  2048.                 this->HandleHighLevelEvent(event);
  2049.                 break;
  2050.  
  2051.             default:
  2052.                 this->HandleAlienEvent(event);
  2053.                 break;
  2054.         }
  2055.     }
  2056. } // TApplication::DispatchEvent 
  2057.  
  2058. //----------------------------------------------------------------------------------------
  2059. // TApplication::DispatchAppleEvent: 
  2060. //----------------------------------------------------------------------------------------
  2061. #pragma segment MAApplicationRes
  2062.  
  2063. OSErr TApplication::DispatchAppleEvent(const AppleEvent& message,
  2064.                                        const AppleEvent& reply,
  2065.                                        long info)
  2066. {
  2067.     OSErr theErr = noErr;
  2068.  
  2069.     // Wrap this in a failure handler so that if failure occured or the event was not
  2070.     // handled we will inform the AppleEvent manager.
  2071.     FailInfo fi;
  2072.     Try(fi)
  2073.     {
  2074.         if (info != cAppleEventReply)
  2075.             this->GetTarget()->HandleAppleCommand(info, message, reply);
  2076.         else
  2077.             // Since the reply is actually in the message, the reply (reply to the reply)
  2078.             // AppleEvent is NULL and can be discarded
  2079.             this->MatchReplyToPending(message);
  2080.         fi.Success();
  2081.     }
  2082.     else
  2083.     {
  2084.         // Since the event was probably suspended, we reset it with AESetTheCurrentEvent
  2085.         // and let the AppleEvent manager will take care of disposing of the event.
  2086.         // Don't resignal here since we HAVE to return through the AppleEvent manager
  2087.         // or the package will remain locked in the system heap (until the next time you
  2088.         // reboot).
  2089.         AESetTheCurrentEvent(&message);
  2090.         theErr = fi.error;
  2091.     }
  2092.     return theErr;
  2093. } // TApplication::DispatchAppleEvent 
  2094.  
  2095. //----------------------------------------------------------------------------------------
  2096. // TApplication::MatchReplyToPending: 
  2097. //----------------------------------------------------------------------------------------
  2098. #pragma segment MAApplicationRes
  2099.  
  2100. void TApplication::MatchReplyToPending(const AppleEvent& reply)
  2101. {
  2102.     TAppleEvent * theReply = NULL;
  2103.     TClientCommand * theMatchedCommand = NULL;
  2104.  
  2105.     theReply = new TAppleEvent;
  2106.     theReply->InitializeFromMessage(reply, false);
  2107.  
  2108.     // Higher priority events are at the end of the list.
  2109.     CObjectIterator iter(fPendingReplyList, kIterateBackward);
  2110.  
  2111.     for (TClientCommand * aCommand = (TClientCommand *)iter.FirstObject(); iter.More(); aCommand = (TClientCommand *)iter.NextObject())
  2112.     {
  2113.         if (aCommand->GetReturnID() == theReply->GetReturnID())
  2114.         {
  2115.             theMatchedCommand = aCommand;
  2116.             break;
  2117.         }
  2118.     }
  2119.  
  2120.     if (theMatchedCommand)
  2121.     {
  2122.         fPendingReplyList->Delete(theMatchedCommand);
  2123.         theMatchedCommand->ProcessReply(theReply);
  2124.         this->PostCommand(theMatchedCommand);
  2125.     }
  2126.     else                                        // No match found
  2127.         theReply = (TAppleEvent *)FreeIfObject(theReply);
  2128. } // TApplication::MatchReplyToPending 
  2129.  
  2130. //----------------------------------------------------------------------------------------
  2131. // TApplication::DoAppleCommand: 
  2132. //----------------------------------------------------------------------------------------
  2133. #pragma segment MAApplicationRes
  2134.  
  2135. void TApplication::DoAppleCommand(CommandNumber aCommandNumber,
  2136.                                   const AppleEvent& message,
  2137.                                   const AppleEvent& reply)
  2138. {
  2139.     switch (aCommandNumber)
  2140.     {
  2141.         case cFinderNew:
  2142.             // Special case the old MacPaint style open if user knows about the option
  2143.             // key. Only if the application is frontmost though.
  2144.             if (this->IsFrontProcess() && IsOptionKeyDown())
  2145.                 this->HandleMenuCommand(cOpen);
  2146.             else if (fLaunchWithNewDocument)
  2147.                 this->GetTarget()->HandleMenuCommand(cFinderNew);
  2148.             break;
  2149.  
  2150.         case cFinderOpen:
  2151.             {
  2152.                 TODocCommand * anODocCommand = new TODocCommand;
  2153.                 anODocCommand->InitializeFromAppleEvent(aCommandNumber, this, kCantUndo, kDoesNotCauseChange, NULL, message, reply);
  2154.                 this->PostCommand(anODocCommand);
  2155.                 break;
  2156.             }
  2157.  
  2158.         case cFinderPrint:
  2159.             {
  2160.                 TPDocCommand * aPDocCommand = new TPDocCommand;
  2161.                 aPDocCommand->InitializeFromAppleEvent(aCommandNumber, this, kCantUndo, kDoesNotCauseChange, NULL, message, reply);
  2162.                 this->PostCommand(aPDocCommand);
  2163.                 break;
  2164.             }
  2165.         case cFinderQuit:
  2166.             this->GetTarget()->HandleMenuCommand(cQuit);
  2167.             break;
  2168.  
  2169.         default:
  2170.             Inherited::DoAppleCommand(aCommandNumber, message, reply);
  2171.             break;
  2172.     }
  2173. } // TApplication::DoAppleCommand 
  2174.  
  2175. //----------------------------------------------------------------------------------------
  2176. // TApplication::DoCommandKeyEvent: 
  2177. //----------------------------------------------------------------------------------------
  2178. #pragma segment MAApplicationRes
  2179.  
  2180. void TApplication::DoCommandKeyEvent(TToolboxEvent* event)// override 
  2181. {
  2182.     if (!event->IsAutoKeyEvent())
  2183.     {
  2184.         this->SetupTheMenus();
  2185.         // If you want to have case sensitive command keys use the following line because
  2186.         // KeyEventToComponents returns the correct character for shifted keys when the
  2187.         // command key is down. That lets us test for things like command-period
  2188.         // correctly. So in order to be backward compatible (sigh) we now have to ignore
  2189.         // the _correct_ char that is passed in (and is in event->fCharacter) and use the
  2190.         // old ToolBox supplied unPasteurized character that is left in the actual
  2191.         // EventRecord
  2192.  
  2193.         // this->MenuEvent(MenuKey(event->fCharacter)); 
  2194.  
  2195.         this->MenuEvent(MenuKey((unsigned char)(((event->fEventRecord.message) & charCodeMask))));
  2196.     }
  2197.     else
  2198.         Inherited::DoCommandKeyEvent(event);
  2199.         
  2200. } // TApplication::DoCommandKeyEvent 
  2201.  
  2202. //----------------------------------------------------------------------------------------
  2203. // TApplication::DoKeyEvent: 
  2204. //----------------------------------------------------------------------------------------
  2205. #pragma segment MAApplicationRes
  2206.  
  2207. void TApplication::DoKeyEvent(TToolboxEvent* event)// override 
  2208. {
  2209.     switch (event->fKeyCode)
  2210.     {
  2211.         case kF1VirtualCode:
  2212.             this->SetupTheMenus();
  2213.             if (CommandEnabled(cUndo))
  2214.                 this->GetTarget()->HandleMenuCommand(cUndo);
  2215.             break;
  2216.  
  2217.         case kF2VirtualCode:
  2218.             this->SetupTheMenus();
  2219.             if (CommandEnabled(cCut))
  2220.                 this->GetTarget()->HandleMenuCommand(cCut);
  2221.             break;
  2222.  
  2223.         case kF3VirtualCode:
  2224.             this->SetupTheMenus();
  2225.             if (CommandEnabled(cCopy))
  2226.                 this->GetTarget()->HandleMenuCommand(cCopy);
  2227.             break;
  2228.  
  2229.         case kF4VirtualCode:
  2230.             this->SetupTheMenus();
  2231.             if (CommandEnabled(cPaste))
  2232.                 this->GetTarget()->HandleMenuCommand(cPaste);
  2233.             break;
  2234.  
  2235.         case kClearVirtualCode:
  2236.             this->SetupTheMenus();
  2237.             if (CommandEnabled(cClear))
  2238.                 this->GetTarget()->HandleMenuCommand(cClear);
  2239.             break;
  2240.  
  2241.         default:
  2242.             Inherited::DoKeyEvent(event);
  2243.             break;
  2244.     }
  2245. } // TApplication::DoKeyEvent 
  2246.  
  2247. //----------------------------------------------------------------------------------------
  2248. // TApplication::DoMakeDocument: 
  2249. //
  2250. // E X A M P L E
  2251. // {
  2252. //         TDocument*    aYOURDocument = NULL;
  2253. //
  2254. //         aYOURDocument = new TDocument;
  2255. //         aYOURDocument->IYOURDocument();
  2256. //        return aYOURDocument;
  2257. // }
  2258. //----------------------------------------------------------------------------------------
  2259. #pragma segment MANever
  2260.  
  2261. TDocument* TApplication::DoMakeDocument(CommandNumber, TFile*)
  2262. {
  2263.     this->SubClassResponsibility();
  2264.     return NULL;                                // So that CFront doesn't complain
  2265. } // TApplication::DoMakeDocument 
  2266.  
  2267. //----------------------------------------------------------------------------------------
  2268. // TApplication::DoMakeFile: 
  2269. //----------------------------------------------------------------------------------------
  2270. #pragma segment MAOpen
  2271.  
  2272. TFile* TApplication::DoMakeFile(CommandNumber)
  2273. {
  2274.     return NewFile(fMainFileType, fCreator, kUsesDataFork, kUsesRsrcFork, !kDataOpen, !kRsrcOpen);
  2275. } // TApplication::DoMakeFile 
  2276.  
  2277. //----------------------------------------------------------------------------------------
  2278. // TApplication::DoMenuCommand: 
  2279. //----------------------------------------------------------------------------------------
  2280. #pragma segment MASelCommand
  2281.  
  2282. void TApplication::DoMenuCommand(CommandNumber aCommandNumber)
  2283. {
  2284.     // ===================================================================================
  2285.     // Some commands will be posted to perform actions that must _ALWAYS_ be available.
  2286.     // The allocation cannot be allowed to fail. So we do a temp allocation which by
  2287.     // definition cannot be allowed to fail. This strategy is used wherever we want to use
  2288.     // command objects but don't want to leave the user twisting in the breeze. NOTE:
  2289.     // Don't forget to allow for this memory in your mem! resource if you copy this style
  2290.     // in your own code.
  2291.     // ===================================================================================
  2292.  
  2293.     Boolean oldObjectPerm;
  2294.     TQuitCommand * aQuitCommand;
  2295.     TNewDocumentCommand * aNewDocCommand;
  2296.     TAboutBoxCommand * aAboutAppCommand;
  2297.     
  2298.     switch (aCommandNumber)
  2299.     {
  2300.         case cQuit:
  2301.             oldObjectPerm = AllocateObjectsFromPerm(false);
  2302.             aQuitCommand = new TQuitCommand;
  2303.             AllocateObjectsFromPerm(oldObjectPerm);
  2304.             aQuitCommand->IQuitCommand(aCommandNumber);
  2305.             this->PostCommand(aQuitCommand);
  2306.             break;
  2307.  
  2308.         case cNew:                                // cNew..cNewLast:
  2309.         case 11:
  2310.         case 12:
  2311.         case 13:
  2312.         case 14:
  2313.         case 15:
  2314.         case 16:
  2315.         case 17:
  2316.         case 18:
  2317.         case cNewLast:
  2318.         case cFinderNew:
  2319.             aNewDocCommand = new TNewDocumentCommand;
  2320.             aNewDocCommand->INewDocumentCommand(aCommandNumber);
  2321.             this->PostCommand(aNewDocCommand);
  2322.             break;
  2323.  
  2324.         case cOpen:                                // cOpen..cOpenLast:
  2325.         case 21:
  2326.         case 22:
  2327.         case 23:
  2328.         case 24:
  2329.         case 25:
  2330.         case 26:
  2331.         case 27:
  2332.         case 28:
  2333.         case cOpenLast:
  2334.             {
  2335.                 TList * aFileList = NULL;
  2336.                 
  2337.                 VOLATILE(aFileList);
  2338.  
  2339.                 if (this->ChooseDocument(aCommandNumber, &aFileList))
  2340.                 {
  2341.                     TODocCommand* anODocCommand = NULL;
  2342.                     
  2343.                     FailInfo fi;
  2344.                     Try(fi)
  2345.                     {
  2346.                         anODocCommand = new TODocCommand;
  2347.                         anODocCommand->IODocCommand(aCommandNumber, aFileList);
  2348.                         fi.Success();
  2349.                     }
  2350.                     else                        // Recover
  2351.                     {
  2352.                         // We can try to free the file list here because at the point where
  2353.                         // IODocCommand could fail, it will not have made the assignment of
  2354.                         // aFileList.
  2355.                         aFileList = (TList *)(FreeIfObject(aFileList));
  2356.                         fi.ReSignal();
  2357.                     }
  2358.                     this->PostCommand(anODocCommand);
  2359.                 }
  2360.                 break;
  2361.             }
  2362.  
  2363.         case cClose:
  2364.             if (qDebug && this->WMgrToWindow(FrontWindow()))
  2365.                 ProgramBreak("The frontmost window is a window object but didn't handle the cClose CommandNumber, your TWindow subclass probably forgot to call Inherited::DoMenuCommand!");
  2366.  
  2367.             this->CloseToolboxWindow(FrontWindow());// TWindow would have handled the command
  2368.             // before we get here so the window is
  2369.             break;                                // probably a DA or something
  2370.  
  2371.         case cAboutApp:
  2372.             aAboutAppCommand = new TAboutBoxCommand;
  2373.             aAboutAppCommand->IAboutBoxCommand(aCommandNumber);
  2374.             this->PostCommand(aAboutAppCommand);
  2375.             break;
  2376.  
  2377. #if qDebug
  2378.         case cDebugFlags:
  2379.             {
  2380.                 if (!fDebugFlagsWindow)
  2381.                     FailNIL(fDebugFlagsWindow = gViewServer->NewTemplateWindow(kDebugFlagsView, NULL));
  2382.                 fDebugFlagsWindow->Open();
  2383.                 fDebugFlagsWindow->Select();
  2384.                 break;
  2385.             }
  2386.  
  2387.         case cRefreshFrontWindow:
  2388.             {
  2389.                 TWindow * aWindow = this->GetActiveWindow(kNoFloaters);
  2390.  
  2391.                 if (aWindow)
  2392.                     aWindow->ForceRedraw();
  2393.                 break;
  2394.             }
  2395.  
  2396.         case cDoFirstClick:
  2397.             {
  2398.                 TWindow * aWindow = this->GetActiveWindow(kNoFloaters);
  2399.  
  2400.                 if (aWindow)
  2401.                     aWindow->fDoFirstClick =!aWindow->fDoFirstClick;
  2402.                 break;
  2403.             }
  2404.  
  2405.         // System Justification - see comment in Debug.r
  2406.     //    case cSetSysJust:
  2407.             // swap the current setting 
  2408.     //        if (GetSysDirection() == smSysJustLeft)
  2409.     //            SetSysDirection(smSysJustRight);
  2410.     //        else
  2411.     //            SetSysDirection(smSysJustLeft);
  2412.     //        break;
  2413. #endif
  2414.  
  2415. #if qPerform
  2416.         case cPerfMonInit:
  2417.             {
  2418.                 TWindow* aWindow;
  2419.                 IDType dismisser;
  2420.                 
  2421.                 FailNIL(aWindow = gViewServer->NewTemplateWindow(kPerfMonInitView, NULL));
  2422.                 dismisser = aWindow->PoseModally();
  2423.                 if (dismisser == 'init')
  2424.                     InitiatePerfMonitor(aWindow);
  2425.                 aWindow->CloseAndFree();
  2426.                 break;
  2427.             }
  2428.             
  2429.         case cPerfMonDump:
  2430.             {
  2431.                 StandardFileReply replyRec;
  2432.                 StandardPutFile((StringPtr)"\pSave as:", (StringPtr)"\puntitled", &replyRec);
  2433.                 if (replyRec.sfGood)
  2434.                     DumpPerfMonitor(replyRec.sfFile);
  2435.                 break;                
  2436.             }
  2437.             
  2438.         case cPerfMonToggle:
  2439.             {
  2440.                 EnablePerfMonitor(!PerfMonitorEnabled());
  2441.                 break;
  2442.             }
  2443.             
  2444.         case cPerfMonEnd:
  2445.             {
  2446.                 TerminatePerfMonitor();
  2447. //MW I added this break; was there a reason it was missing?
  2448.                 break;
  2449.             }
  2450. #endif
  2451.             
  2452.         default:
  2453.             Inherited::DoMenuCommand(aCommandNumber);
  2454.             break;
  2455.     }
  2456. } // TApplication::DoMenuCommand 
  2457.  
  2458. //----------------------------------------------------------------------------------------
  2459. // TApplication::DoSetupMenus: 
  2460. //----------------------------------------------------------------------------------------
  2461. #pragma segment MAApplicationRes
  2462.  
  2463. void TApplication::DoSetupMenus()
  2464. {
  2465.     Inherited::DoSetupMenus();
  2466.  
  2467.     gMenuBarManager->SetPreferredMenuBarID(fDisplayedMenus);
  2468.     gMenuBarManager->SetPreferredHierMenuBarID(fMBarHierarchical);
  2469.  
  2470.     Boolean lowSpace = MemSpaceIsLow();
  2471.  
  2472.     Enable(cAboutApp, true);
  2473.  
  2474.     Enable(cQuit, fEventLevel <= 1);    // Can't enable Quit if in nested event handling
  2475.     Enable(cNew, !lowSpace);
  2476.     Enable(cOpen, !lowSpace);
  2477.  
  2478.     WindowPtr aWindowPtr = FrontWindow();
  2479.     if ((aWindowPtr) && (this->WMgrToWindow(aWindowPtr) == NULL))
  2480.         // window objects will take care of themselves, but we take care of the indigent.
  2481.         Enable(cClose, ((WindowPeek)aWindowPtr)->goAwayFlag != false);
  2482. } // TApplication::DoSetupMenus 
  2483.  
  2484. //----------------------------------------------------------------------------------------
  2485. // TApplication::DoAboutBox: Method to display the "About" box for your application.
  2486. // Override to do interesting things. Since it is normally called from a command; the app
  2487. // usually has the maximum free space available.
  2488. //----------------------------------------------------------------------------------------
  2489. #pragma segment MAAboutApp
  2490.  
  2491. void TApplication::DoAboutBox()
  2492. {
  2493.     CStr255 apName;
  2494.  
  2495.     FailSpaceIsLow();
  2496.     this->GetApplicationName(apName);
  2497.     ParamText((ConstStr255Param)&apName, (ConstStr255Param)&gEmptyString,
  2498.         (ConstStr255Param)&gEmptyString, (ConstStr255Param)&gEmptyString);                // Put Application name in the about box 
  2499.     hadCreditsStringList = (GetResource('STR#', kDefaultCredits) != NULL);
  2500.     if (hadCreditsStringList)
  2501.     {
  2502.         lastCreditsStringIndex = 1;
  2503.         lastCreditsShownTicks = TickCount();
  2504.         waitTicks = 5 * 60;
  2505.         originalText = (CStringHandle)NewString(gEmptyString);
  2506.         FailNIL(originalText);
  2507.         MacAppAlert(phAboutApp, (ProcPtr) & DoShowAboutAppFilter);
  2508.         originalText = (CStringHandle)DisposeIfHandle((Handle)originalText);
  2509.     }
  2510.     else
  2511.         StdAlert(phAboutApp);
  2512. } // TApplication::DoAboutBox 
  2513.  
  2514. //----------------------------------------------------------------------------------------
  2515. // TApplication::DoMakeDependencySpace: 
  2516. //----------------------------------------------------------------------------------------
  2517. #pragma segment MAInit
  2518.  
  2519. void TApplication::DoMakeDependencySpace()
  2520. {
  2521.     TSimpleDependencySpace* aDependencySpace = NULL;
  2522.     
  2523.     aDependencySpace = new TSimpleDependencySpace;
  2524.     aDependencySpace->ISimpleDependencySpace();
  2525.     
  2526.     gMacAppDependencies = aDependencySpace;
  2527. }
  2528.  
  2529. //----------------------------------------------------------------------------------------
  2530. // TApplication::GetDefaultCursorRegion: Make the region the desktop less the active
  2531. // window, and any first click windows. The current mouse location is added in
  2532. // TApplication::TrackCursor.
  2533. //----------------------------------------------------------------------------------------
  2534. void TApplication::GetDefaultCursorRegion(CPoint /* globalMouse */,
  2535.                                           RgnHandle cursorRegion)
  2536. {
  2537.     // Start off with the "desktop region" 
  2538.     GetDeskTopRegion(cursorRegion);
  2539.  
  2540.     // Remove the visRgn of all windows for which TestWindow returns true 
  2541.     CWMgrIterator iter;
  2542.  
  2543.     for (WindowPtr aWinPtr = iter.FirstWMgrWindow(); iter.More(); aWinPtr = iter.NextWMgrWindow())
  2544.     {
  2545.         TWindow * aWindow = this->WMgrToWindow(aWinPtr);
  2546.  
  2547.         if (aWindow && (aWindow->IsShown() && aWindow->HandlesCursor()) && aWindow->Focus())
  2548.         {
  2549.             // Convert the visRgn to global coordinates. We focused on the window because
  2550.             // the visRgn is in the coordinates of the current port
  2551.             aWindow->LocalToSuperRegion(aWinPtr->visRgn);
  2552.  
  2553.             // Remove the visRgn from the cursor region 
  2554.             DiffRgn(cursorRegion, aWinPtr->visRgn, cursorRegion);
  2555.  
  2556.             // Convert the visRgn back to local (port) coordinates 
  2557.             aWindow->SuperToLocalRegion(aWinPtr->visRgn);
  2558.         }
  2559.     }
  2560. } // TApplication::GetDefaultCursorRegion 
  2561.  
  2562. //----------------------------------------------------------------------------------------
  2563. // TApplication::InstallHelpMenuItems: 
  2564. //----------------------------------------------------------------------------------------
  2565. #pragma segment MAApplicationRes
  2566. void TApplication::InstallHelpMenuItems()
  2567. {
  2568.     // abstract method; override to install your help menu item(s).  Use
  2569.     // gMenuBarManager->AddHelpMenuItem( "^0 Help", kYourHelpCommandNumber );
  2570. } // TApplication::InstallHelpMenuItems 
  2571.  
  2572. //----------------------------------------------------------------------------------------
  2573. // TApplication::GetDefaultHelpRegion: Make the region the desktop less the active window,
  2574. // and any first click windows. The current mouse location is added in
  2575. // TApplication::TrackHelp.
  2576. //----------------------------------------------------------------------------------------
  2577. void TApplication::GetDefaultHelpRegion(CPoint /* globalMouse */,
  2578.                                         RgnHandle helpRegion)
  2579. {
  2580.     // Start off with the "desktop region" 
  2581.     GetDeskTopRegion(helpRegion);
  2582.  
  2583.     // Remove the visRgn of all windows for which TestWindow returns true 
  2584.     CWMgrIterator iter;
  2585.  
  2586.     for (WindowPtr aWinPtr = iter.FirstWMgrWindow(); iter.More(); aWinPtr = iter.NextWMgrWindow())
  2587.     {
  2588.         TWindow * aWindow = this->WMgrToWindow(aWinPtr);
  2589.  
  2590.         if (aWindow && (aWindow->IsShown() && aWindow->HandlesHelp()) && aWindow->Focus())
  2591.         {
  2592.             // Convert the visRgn to global coordinates. We focused on the window because
  2593.             // the visRgn is in the coordinates of the current port
  2594.             aWindow->LocalToSuperRegion(aWinPtr->visRgn);
  2595.  
  2596.             // Remove the visRgn from the cursor region 
  2597.             DiffRgn(helpRegion, aWinPtr->visRgn, helpRegion);
  2598.  
  2599.             // Convert the visRgn back to local (port) coordinates 
  2600.             aWindow->SuperToLocalRegion(aWinPtr->visRgn);
  2601.         }
  2602.     }
  2603. } // TApplication::GetDefaultHelpRegion 
  2604.  
  2605. //----------------------------------------------------------------------------------------
  2606. // TApplication::GetHelpParameters: 
  2607. //----------------------------------------------------------------------------------------
  2608. #pragma segment MAApplicationRes
  2609.  
  2610. void TApplication::GetHelpParameters(ResNumber helpResource,
  2611.                                      short helpIndex,
  2612.                                      short helpState,
  2613.                                      HMMessageRecord& helpMessage,
  2614.                                      CPoint& localQDTip,
  2615.                                      CRect& localQDRect,
  2616.                                      short& balloonVariant)
  2617. {
  2618.     long options;
  2619.     short theProc;
  2620.     short count;
  2621.     short oldResFile;
  2622.     
  2623.     VOLATILE(oldResFile);
  2624.  
  2625.     FailInfo fi;
  2626.     
  2627.     oldResFile = CurResFile();
  2628.     
  2629.     Try(fi)
  2630.     {
  2631.         UseResFile(gApplicationRefNum);
  2632.         
  2633.         FailOSErr(HMGetIndHelpMsg(kHMDialogResType, 
  2634.                                 helpResource, helpIndex,helpState,
  2635.                                 &options, localQDTip, localQDRect, &theProc, &balloonVariant, &helpMessage, &count));
  2636.         fi.Success();
  2637.     }
  2638.     else
  2639.     {
  2640.         UseResFile(oldResFile);
  2641.         fi.ReSignal();
  2642.     }
  2643.     UseResFile(oldResFile);
  2644. } // TApplication::GetHelpParameters 
  2645.  
  2646. //----------------------------------------------------------------------------------------
  2647. // TApplication::GetSleepRegion: 
  2648. //----------------------------------------------------------------------------------------
  2649. #pragma segment MAApplicationRes
  2650.  
  2651. RgnHandle TApplication::GetSleepRegion()
  2652. {
  2653.     if (this->IsFrontProcess())
  2654.     {
  2655.         // Compute based on where the mouse is right NOW 
  2656.         CPoint globalMouse;
  2657.  
  2658.         GetMouse(globalMouse);
  2659.         LocalToGlobal(globalMouse);
  2660.  
  2661.         Boolean isSleepInvalid = false;
  2662.  
  2663.         // The help region is computed before the cursor rgn so that
  2664.         // the cursor region excludes the balloon shape
  2665.         if ((this->IsHelpRgnInvalid()) && (this->IsHelpEnabled()))
  2666.         {
  2667.             this->TrackHelp(globalMouse);
  2668.             isSleepInvalid = true;
  2669.         }
  2670.  
  2671.         if (this->IsCursorRgnInvalid())
  2672.         {
  2673.             this->TrackCursor(globalMouse);
  2674.             isSleepInvalid = true;
  2675.         }
  2676.  
  2677.         if (isSleepInvalid)
  2678.             if (this->IsHelpEnabled())
  2679.                 SectRgn(fCursorRegion, fHelpRegion, fSleepRegion);
  2680.             else
  2681.                 CopyRgn(fCursorRegion, fSleepRegion);
  2682.  
  2683.         // Ensure that the sleep region contains the mouse. 
  2684.         PtAndRgn(globalMouse, fSleepRegion);
  2685.  
  2686.         return fSleepRegion;
  2687.     }
  2688.     else
  2689.         return NULL;
  2690. } // TApplication::GetSleepRegion 
  2691.  
  2692. //----------------------------------------------------------------------------------------
  2693. // TApplication::GetEvent: 
  2694. //----------------------------------------------------------------------------------------
  2695. #pragma segment MAApplicationRes
  2696.  
  2697. TToolboxEvent* TApplication::GetEvent(short eventMask,
  2698.                                       long sleep,
  2699.                                       RgnHandle sleepRegion)
  2700. {
  2701.     TToolboxEvent * returnEvent = NULL;
  2702.  
  2703. #if qDebug
  2704.     --gRsrcCheck;
  2705.     if (gRsrcCheck <= 0)
  2706.     {
  2707.         CheckRsrcUsage();
  2708.         gRsrcCheck = kRsrcCheckInterval;
  2709.     }
  2710. #endif
  2711.  
  2712.     if (gIntenseDebugging && gReportEvent)
  2713.     {
  2714.         fprintf(stderr, "WaitNextEvent: sleep=0%d", sleep);
  2715.         // faceless driver bug fixed in MF 7.0 
  2716.         if (sleepRegion == NULL)
  2717.             fprintf(stderr, ", sleep region=NULL");
  2718.         else
  2719.         {
  2720.             CRect bBox = (*sleepRegion)->rgnBBox;
  2721.             fprintf(stderr, ", sleep region = %s", (char*) bBox);
  2722.         }
  2723.         fprintf(stderr, "\n");
  2724.  
  2725.     }
  2726.  
  2727. #if qDebug
  2728.     if (gShowCursorRegion || gShowHelpRegion || gShowSleepRegion)
  2729.     {
  2730.         CGrafPort desktopPort;                    // Used for showing cursor region 
  2731.         long ticks;                                // Used for showing cursor region 
  2732.         GrafPtr savedPort;                        // Used for showing cursor region 
  2733.  
  2734.         // Cursor region is in global coords. Need to create desktop port 
  2735.         GetPort(&savedPort);
  2736.         if (qNeedsColorQD || gConfiguration.hasColorQD)
  2737.             OpenCPort(&desktopPort);
  2738.         else
  2739.             OpenPort((GrafPtr) & desktopPort);
  2740.         CopyRgn(GetGrayRgn(), desktopPort.visRgn);
  2741.         desktopPort.portRect = (*(desktopPort.visRgn))->rgnBBox;
  2742.  
  2743.         PenNormal();
  2744.         PenMode(patXor);
  2745.  
  2746.         if (gShowCursorRegion)
  2747.         {
  2748.             PaintRgn(fCursorRegion);
  2749.             Delay(30, &ticks);
  2750.             PaintRgn(fCursorRegion);
  2751.         }
  2752.  
  2753.         if (gShowHelpRegion)
  2754.         {
  2755.             PaintRgn(fHelpRegion);
  2756.             Delay(30, &ticks);
  2757.             PaintRgn(fHelpRegion);
  2758.         }
  2759.  
  2760.         if (gShowSleepRegion)
  2761.         {
  2762.             PaintRgn(fSleepRegion);
  2763.             Delay(30, &ticks);
  2764.             PaintRgn(fSleepRegion);
  2765.         }
  2766.  
  2767.         sleep = 60;
  2768.  
  2769.         if (qNeedsColorQD || gConfiguration.hasColorQD)
  2770.             CloseCPort(&desktopPort);
  2771.         else
  2772.             ClosePort((GrafPtr) & desktopPort);
  2773.         SetPort(savedPort);
  2774.     }
  2775.  
  2776. #endif
  2777.  
  2778.     // If we are in a nested event level than don't turn off the busy cursor since we are
  2779.     // probably in the middle of an idle or filter proc and don't want to turn on and off
  2780.     // the busy cursor each time it gets to service an event.
  2781.     if (fEventLevel <= 1)
  2782.         this->ActivateBusyCursor(false);            // Turn off busy cursor while we're away.
  2783.  
  2784. #if qPerform
  2785.     Boolean oldSetting = PerfMonitorEnabled();
  2786. #endif
  2787.  
  2788.     // SystemEvents aren't queued and will be lost if not retrieved when available. So we
  2789.     // ensure here that they are always retrieved by adding osMask.
  2790.     EventRecord anEvent;
  2791.  
  2792.     if (WaitNextEvent(((eventMask) | osMask), &anEvent, sleep, sleepRegion))
  2793.     {
  2794.         Boolean oldObjectPerm = AllocateObjectsFromPerm(false);
  2795.         returnEvent = new TToolboxEvent;
  2796.         AllocateObjectsFromPerm(oldObjectPerm);
  2797.         returnEvent->IToolboxEvent(this, anEvent);
  2798.     }
  2799.  
  2800. #if qPerform
  2801.     EnablePerfMonitor(oldSetting);
  2802. #endif
  2803.  
  2804.     if (this->IsFrontProcess())                 // If we're not in the background, then 
  2805.         this->ActivateBusyCursor(true);            // …enable the busy cursor mechanism. 
  2806.  
  2807.     return returnEvent;
  2808. } // TApplication::GetEvent 
  2809.  
  2810. //----------------------------------------------------------------------------------------
  2811. // TApplication::GetFrontWindow: 
  2812. //----------------------------------------------------------------------------------------
  2813. #pragma segment MAApplicationRes
  2814.  
  2815. TWindow* TApplication::GetFrontWindow()
  2816. {
  2817.     if (qNeedsProcessMgr || gConfiguration.hasProcessMgr ||!IsDeskAccessory(FrontWindow()))
  2818.     {
  2819.         CWMgrIterator iter;
  2820.  
  2821.         for (WindowPtr aWinPtr = iter.FirstWMgrWindow(); iter.More(); aWinPtr = iter.NextWMgrWindow())
  2822.         {
  2823.             TWindow * aWindow = this->WMgrToWindow(aWinPtr);
  2824.  
  2825.             if ((aWindow) && (aWindow->IsShown()) && (!aWindow->fFloats))
  2826.                 return aWindow;
  2827.         }
  2828.     }
  2829.     return NULL;
  2830. } // TApplication::GetFrontWindow 
  2831.  
  2832. //----------------------------------------------------------------------------------------
  2833. // TApplication::GetActiveWindow: 
  2834. //----------------------------------------------------------------------------------------
  2835. #pragma segment MAApplicationRes
  2836.  
  2837. TWindow* TApplication::GetActiveWindow(Boolean floatersAreOkay)
  2838. {
  2839.     if (qNeedsProcessMgr || gConfiguration.hasProcessMgr ||!IsDeskAccessory(FrontWindow()))
  2840.     {
  2841.         CWMgrIterator iter;
  2842.  
  2843.         for (WindowPtr aWinPtr = iter.FirstWMgrWindow(); iter.More(); aWinPtr = iter.NextWMgrWindow())
  2844.         {
  2845.             TWindow * aWindow = this->WMgrToWindow(aWinPtr);
  2846.  
  2847.             if ((aWindow) && (aWindow->IsShown()) && (aWindow->IsActive()))
  2848.             {
  2849.                 if (aWindow->fFloats)
  2850.                 {
  2851.                     if (floatersAreOkay)
  2852.                         return aWindow;
  2853.                 }
  2854.                 else
  2855.                     return aWindow;
  2856.             }
  2857.         }
  2858.     }
  2859.     return NULL;
  2860. } // TApplication::GetActiveWindow 
  2861.  
  2862. //----------------------------------------------------------------------------------------
  2863. // TApplication::RetrieveAnEvent: 
  2864. //----------------------------------------------------------------------------------------
  2865. #pragma segment MAApplicationRes
  2866.  
  2867. TEvent* TApplication::RetrieveAnEvent()
  2868. {
  2869.     TEvent* returnEvent = NULL;
  2870.  
  2871.     // Higher priority events are at the end of the list.
  2872.     CEventListIterator iter(fEventList);
  2873.  
  2874.     for (TEvent *itsEvent = iter.FirstEvent(); iter.More(); itsEvent = iter.NextEvent())
  2875.     {
  2876.         if (itsEvent->IsReadyToExecute())
  2877.         {
  2878.             returnEvent = itsEvent;
  2879.             break;
  2880.         }
  2881.     }
  2882.  
  2883.     if ((returnEvent) &&!returnEvent->IsRecurring())
  2884.         fEventList->Delete(returnEvent);
  2885.  
  2886.     return returnEvent;
  2887. } // TApplication::RetrieveAnEvent 
  2888.  
  2889. //----------------------------------------------------------------------------------------
  2890. // TApplication::NewToolboxWindow: 
  2891. //----------------------------------------------------------------------------------------
  2892. #pragma segment MAOpen
  2893.  
  2894. #if defined(powerc) || defined(__powerc)
  2895. #pragma options align=mac68k
  2896. #endif
  2897. struct WINDTemplate
  2898. {
  2899.     CRect bounds;
  2900.     short procID;
  2901.     Boolean visible;
  2902.     Boolean filler1;
  2903.     Boolean goAway;
  2904.     Boolean filler2;
  2905.     long refcon;
  2906.     short itemsID;                            // only for DLOG resource 
  2907. };
  2908. #if defined(powerc) || defined(__powerc)
  2909. #pragma options align=reset
  2910. #endif
  2911.  
  2912. typedef struct WINDTemplate WINDTemplate;
  2913. typedef WINDTemplate* WINDTemplatePtr, **WINDTemplateHandle;
  2914.  
  2915. WindowPtr TApplication::NewToolboxWindow(Ptr storage,
  2916.                                          short rsrcId,
  2917.                                          Boolean& isResizable,
  2918.                                          Boolean& isClosable)
  2919. {
  2920.     // We force INVISIBLE in the WIND definition so the screen won't flash. 
  2921.     WindowPtr aWMgrWindow;
  2922.     WINDTemplateHandle templateHandle;
  2923.  
  2924.     Boolean oldPerm;
  2925.  
  2926.     VOLATILE(oldPerm);
  2927.  
  2928.     // Even though the window is permanent, we allocate it under a temporary flag so that the
  2929.     // maximum memory is available. Quickdraw can blow up if it can't allocate a grafPort.
  2930.     oldPerm = PermAllocation(false);
  2931.  
  2932.     FailInfo fi;
  2933.     Try(fi)
  2934.     {
  2935.         templateHandle = (WINDTemplateHandle)GetResource('WIND', rsrcId);
  2936.         FailNILResource((Handle)templateHandle);
  2937.         MoveHHi((Handle)templateHandle);        // in case it is locked by the ROM 
  2938.  
  2939.         WINDTemplate & templateData = **templateHandle;
  2940.         templateData.visible = false;
  2941.         isClosable = templateData.goAway;
  2942.         isResizable = ((templateData.procID == documentProc) || (templateData.procID == zoomDocProc));
  2943.         // If your own defProc is resizable, too, then after the call on NewToolboxWindow, set
  2944.         // isResizable true 
  2945.         
  2946.         WindowPtr putWindowBehind = GetLastFloatingWindowPtr();
  2947.         if (putWindowBehind == NULL)
  2948.             putWindowBehind = (WindowPtr) -1;
  2949.         
  2950.         if (qNeedsColorQD || gConfiguration.hasColorQD)
  2951.             aWMgrWindow = (WindowPtr)(GetNewCWindow(rsrcId, (Ptr)(storage), putWindowBehind));
  2952.         else
  2953.             aWMgrWindow = GetNewWindow(rsrcId, (Ptr)(storage), putWindowBehind);
  2954.  
  2955.         FailNIL(aWMgrWindow);
  2956.         oldPerm = PermAllocation(oldPerm);
  2957.         fi.Success();
  2958.     }
  2959.     else                                        // Recover. Don't need the failure handler since we've set the perm allocation flag back.
  2960.         {
  2961.             // Make sure the perm allocation flag is set back to what it was
  2962.             // when we entered NewToolboxWindow.
  2963.             oldPerm = PermAllocation(oldPerm);
  2964.             fi.ReSignal();
  2965.         }
  2966.  
  2967.     // Now we must make sure that the code reserve is still intact.
  2968.     if (!CheckReserve())
  2969.     {
  2970.         aWMgrWindow = FreeIfWMgrWindow(aWMgrWindow, storage == NULL);
  2971.  
  2972.         Failure(memFullErr, 0);
  2973.     }
  2974.  
  2975.     return aWMgrWindow;
  2976. } // TApplication::NewToolboxWindow 
  2977.  
  2978. //----------------------------------------------------------------------------------------
  2979. // TApplication::GetTarget: 
  2980. //----------------------------------------------------------------------------------------
  2981. #pragma segment MAApplicationRes
  2982.  
  2983. TEventHandler* TApplication::GetTarget()
  2984. {
  2985.     return fTarget;
  2986. } // TApplication::GetTarget 
  2987.  
  2988. //----------------------------------------------------------------------------------------
  2989. // TApplication::HandleActivateEvent: 
  2990. //----------------------------------------------------------------------------------------
  2991. #pragma segment MAApplicationRes
  2992.  
  2993. void TApplication::HandleActivateEvent(TToolboxEvent* event)
  2994. {
  2995.     TWindow * aWindow = this->WMgrToWindow((WindowPtr)(event->fEventRecord.message));
  2996.     if (aWindow)
  2997.     {
  2998.         Boolean activate = ((event->fEventRecord.modifiers) & activeFlag) != 0;
  2999.         if (aWindow->fFloats)                                // ignore floaters
  3000.         {
  3001.             TWindow* frontWindow = this->GetFrontWindow();    // find frontmost non-floating window
  3002.             if (frontWindow)
  3003.             {
  3004.                 aWindow = frontWindow;                        // (de)activate it instead of the floater
  3005.                 HiliteWindow(aWindow->fWMgrWindow, activate);
  3006.             }
  3007.         }
  3008.         aWindow->Activate(activate);
  3009.     }
  3010.     else
  3011.         this->HandleAlienEvent(event);
  3012. } // TApplication::HandleActivateEvent 
  3013.  
  3014. //----------------------------------------------------------------------------------------
  3015. // TApplication::HandleAlienEvent: 
  3016. //----------------------------------------------------------------------------------------
  3017. #pragma segment MAApplicationRes
  3018.  
  3019. void TApplication::HandleAlienEvent(TToolboxEvent* event)
  3020. {
  3021.     CHandlerIterator iter(fHeadCohandler);
  3022.  
  3023.     for (TEventHandler * aHandler = iter.FirstHandler(); iter.More(); aHandler = iter.NextHandler())
  3024.         if (aHandler->DoCoHandlerEvent(event))
  3025.             break;
  3026. } // TApplication::HandleAlienEvent 
  3027.  
  3028. //----------------------------------------------------------------------------------------
  3029. // TApplication::HandleDiskEvent: 
  3030. //----------------------------------------------------------------------------------------
  3031. #pragma segment MADoCommand
  3032.  
  3033. void TApplication::HandleDiskEvent(TToolboxEvent* event)
  3034. {
  3035.     if (HiWord(event->fEventRecord.message) != noErr)
  3036.     {
  3037.         Point topLeft;
  3038.         
  3039.         SetPt(&topLeft,112,80);
  3040.  
  3041.         short err = DIBadMount(topLeft, event->fEventRecord.message);
  3042. #if qDebugMsg
  3043.         if (err != noErr)
  3044.             fprintf(stderr, "error from DIBadMount is %d\n", err);
  3045. #endif
  3046.  
  3047.     }
  3048. } // TApplication::HandleDiskEvent 
  3049.  
  3050. //----------------------------------------------------------------------------------------
  3051. // TApplication::DoToolboxEvent: 
  3052. //----------------------------------------------------------------------------------------
  3053. #pragma segment MAApplicationRes
  3054.  
  3055. void TApplication::DoToolboxEvent(TToolboxEvent* event)
  3056. {
  3057. #if qDebug
  3058.     if (gReportEvent && event)
  3059.         event->ReportEvent();
  3060. #endif
  3061.  
  3062.     this->DispatchEvent(event);
  3063. } // TApplication::DoToolboxEvent 
  3064.  
  3065. //----------------------------------------------------------------------------------------
  3066. // TApplication::HandleFinderRequest: 
  3067. //----------------------------------------------------------------------------------------
  3068. #pragma segment MAFinder
  3069.  
  3070. void TApplication::HandleFinderRequest()
  3071. {
  3072. #if !qNeedsAppleEventMgr
  3073.  
  3074.     TFile * aFile;
  3075.     short message;
  3076.     AppFile anAppFile;
  3077.     CommandNumber command;
  3078.  
  3079.     VOLATILE(aFile);
  3080.     VOLATILE(message);
  3081.     VOLATILE(anAppFile);
  3082.     VOLATILE(command);
  3083.  
  3084.     FailInfo outerFi;
  3085.     Try(outerFi)
  3086.     {
  3087.         // determine number of files and whether it's a print from finder request 
  3088.         short theFileCount;
  3089.  
  3090.         CountAppFiles(&message, &theFileCount);
  3091.  
  3092.         Boolean finderPrinting = (message == appPrint);
  3093.  
  3094.         if (theFileCount == 0)
  3095.         {
  3096.             if (this->IsFrontProcess() && IsOptionKeyDown())
  3097.                 this->HandleMenuCommand(cOpen);
  3098.             else if (fLaunchWithNewDocument)
  3099.                 this->HandleMenuCommand(cFinderNew);
  3100.         }
  3101.         else                        // it's an OPEN or PRINT of 1 or more existing files
  3102.         {
  3103.             if (finderPrinting)
  3104.                 command = cFinderPrint;
  3105.             else
  3106.                 command = cFinderOpen;
  3107.  
  3108.             TList * aFileList = NewList();
  3109.  
  3110.             for (short i = 1; i <= theFileCount; ++i)
  3111.             {
  3112.                 FailInfo fi;
  3113.                 Try(fi)
  3114.                 {
  3115.                     aFile = this->DoMakeFile(command);
  3116.  
  3117.                     GetAppFiles(i, &anAppFile);
  3118.  
  3119.                     FailOSErr(aFile->SpecifyWithTrio(anAppFile.vRefNum, 0, (const CStr63 &) anAppFile.fName));
  3120.                     aFile->fFileType = anAppFile.fType;
  3121.  
  3122.                     ClrAppFiles(i);
  3123.                     aFileList->InsertLast(aFile);
  3124.                     fi.Success();
  3125.                 }
  3126.                 else                        // Recover
  3127.                 {
  3128.                     if (fi.error != noErr)
  3129.                     {
  3130.                         aFile = (TFile *)(FreeIfObject(aFile));
  3131.                         if (fi.message == 0)
  3132.                         {
  3133.                             gErrorParm3 = (CStr255)anAppFile.fName;
  3134.                             if (command == cFinderPrint)
  3135.                                 fi.message = messagePrintFailed;
  3136.                             else
  3137.                                 fi.message = messageOpenFailed;
  3138.                         }
  3139.                         this->ShowError(fi.error, fi.message);
  3140.                     }
  3141.                 }
  3142.             }
  3143.  
  3144.             if (finderPrinting)
  3145.             {
  3146.                 TPDocCommand * aPDocCommand;
  3147.  
  3148.                 aPDocCommand = new TPDocCommand;
  3149.                 aPDocCommand->IPDocCommand(cFinderPrint, aFileList);
  3150.                 this->PostCommand(aPDocCommand);
  3151.             }
  3152.             else
  3153.             {
  3154.                 TODocCommand * anODocCommand;
  3155.  
  3156.                 anODocCommand = new TODocCommand;
  3157.                 anODocCommand->IODocCommand(cFinderOpen, aFileList);
  3158.                 this->PostCommand(anODocCommand);
  3159.             }
  3160.         }
  3161.         outerFi.Success();
  3162.     }
  3163.     else                                        // Recover
  3164.     {
  3165.         if (outerFi.error != noErr)
  3166.             this->ShowError(outerFi.error, outerFi.message);// PollEvents' error handler not in place yet
  3167.     }
  3168. #endif
  3169.  
  3170. } // TApplication::HandleFinderRequest 
  3171.  
  3172. //----------------------------------------------------------------------------------------
  3173. // TApplication::HandleHighLevelEvent: Assume that the high level event received was an
  3174. // Apple Event and process it. This will dispatch to us via MAGeneralDispatch.
  3175. //----------------------------------------------------------------------------------------
  3176. #pragma segment MAApplicationRes
  3177.  
  3178. void TApplication::HandleHighLevelEvent(TToolboxEvent* event)
  3179. {
  3180.     this->SetupTheMenus();                        // Make sure that the menus are setup
  3181.     // correctly before we handle the event
  3182.     EventRecord anEventRecord = event->fEventRecord;
  3183.  
  3184.     OSErr theErr = AEProcessAppleEvent(&anEventRecord);
  3185.     if (theErr != errAEEventNotHandled)            // If the event is one we don't handle, do nothing
  3186.         FailOSErr(theErr);
  3187. } // TApplication::HandleHighLevelEvent 
  3188.  
  3189. //----------------------------------------------------------------------------------------
  3190. // TApplication::HandleKeyDownEvent: 
  3191. //----------------------------------------------------------------------------------------
  3192. #pragma segment MAApplicationRes
  3193.  
  3194. void TApplication::HandleKeyDownEvent(TToolboxEvent* event)
  3195. {
  3196.     this->GetTarget()->KeyEventToComponents(event);// Find out what keys were _REALLY_ pressed 
  3197.  
  3198.     if (event->IsCommandKeyPressed())
  3199.         this->GetTarget()->HandleCommandKey(event);
  3200.     else
  3201.         this->GetTarget()->HandleKeyCommand(event);
  3202. } // TApplication::HandleKeyDownEvent 
  3203.  
  3204. //----------------------------------------------------------------------------------------
  3205. // TApplication::HandleKeyUpEvent: 
  3206. //----------------------------------------------------------------------------------------
  3207. #pragma segment MAApplicationRes
  3208.  
  3209. void TApplication::HandleKeyUpEvent(TToolboxEvent* event)
  3210. {
  3211.     // We don't think KeyUp events should affect the menus.
  3212.     event->fAffectsMenus = false;
  3213.     
  3214.     this->GetTarget()->KeyEventToComponents(event);// Find out what keys were _REALLY_ released 
  3215.  
  3216.     this->GetTarget()->HandleKeyUp(event);
  3217. } // TApplication::HandleKeyUpEvent 
  3218.  
  3219. //----------------------------------------------------------------------------------------
  3220. // TApplication::HandleMouseDown: 
  3221. //----------------------------------------------------------------------------------------
  3222. #pragma segment MAApplicationRes
  3223.  
  3224. void TApplication::HandleMouseDown(TToolboxEvent* event)
  3225. {
  3226.     WindowPtr aWMgrWindow;
  3227.  
  3228.     short whereMouseDown = FindWindow(event->fEventRecord.where, &aWMgrWindow);
  3229.     event->fClickCount = this->CountClicks(event, whereMouseDown);
  3230.  
  3231.     TWindow * aWindow = this->WMgrToWindow(aWMgrWindow);
  3232.  
  3233.     if ((whereMouseDown != inMenuBar) && this->InModalState() && (aWindow != (this->GetActiveWindow(kNoFloaters))))
  3234.     {
  3235.         this->Beep(2);
  3236.         return;                                    // exit(HandleMouseDown);
  3237.     }
  3238.  
  3239.     switch (whereMouseDown)
  3240.     {
  3241.         case inMenuBar:
  3242.             this->SetupTheMenus();                // gives application a chance to setup individual menu items
  3243.             SetCursor(&(qd.arrow));
  3244.             this->MenuEvent(MenuSelect(event->fEventRecord.where));
  3245.             break;
  3246.  
  3247.         case inSysWindow:
  3248.             {
  3249.                 EventRecord anEventRecord = event->fEventRecord;
  3250.                 SystemClick(&anEventRecord, aWMgrWindow);
  3251.                 break;
  3252.             }
  3253.  
  3254.         default:                                // if a MacApp window was associated with the WindowPtr then let the window object decide
  3255.             // what to do with the mouse click
  3256.             if (aWindow)
  3257.             {
  3258.                 if (aWindow->Focus())            // if we can't focus, we're in trouble 
  3259.                 {
  3260.                     VPoint theMouse(event->fEventRecord.where);
  3261.                     aWindow->SuperToLocal(theMouse);
  3262.                     aWindow->HandleMouseDown(theMouse, event, gStdHysteresis);
  3263.                 }
  3264. #if qDebug
  3265.                 else
  3266.                     ProgramBreak("In TApplication::HandleMouseDown: couldn't focus on a window object!");
  3267. #endif
  3268.             }
  3269.             else
  3270.                 this->HandleAlienEvent(event);
  3271.             break;
  3272.  
  3273.     }
  3274.     fLastUpTime = TickCount();                    // Because the toolbox often eats mouseUpEvents remember the time on the way out for
  3275.     // double/ triple detection.
  3276. } // TApplication::HandleMouseDown 
  3277.  
  3278. //----------------------------------------------------------------------------------------
  3279. // TApplication::HandleMouseUp: 
  3280. //----------------------------------------------------------------------------------------
  3281. #pragma segment MAApplicationRes
  3282.  
  3283. void TApplication::HandleMouseUp(TToolboxEvent* event)
  3284. {
  3285.     // now we _Really_ know what the last mouse up time is.
  3286.     // Remember time of last mouse up, in order to detect double/triple (multiple) clicks 
  3287.     fLastUpTime = event->fEventRecord.when;
  3288.  
  3289.     WindowPtr aWMgrWindow;
  3290.     short whereMouseDown = FindWindow(event->fEventRecord.where, &aWMgrWindow);
  3291.  
  3292.     switch (whereMouseDown)
  3293.     {
  3294.         case inMenuBar:
  3295.             break;
  3296.  
  3297.         case inSysWindow:
  3298.             break;
  3299.  
  3300.         default:                                // if a MacApp window was associated with the WindowPtr then let the window object decide
  3301.             {
  3302.                 TWindow * aWindow = this->WMgrToWindow(aWMgrWindow);
  3303.  
  3304.                 // what to do with the mouse click
  3305.                 if (aWindow)
  3306.                 {
  3307.                     if (aWindow->Focus())        // if we can't focus, we're in trouble 
  3308.                     {
  3309.                         VPoint theMouse(event->fEventRecord.where);
  3310.                         aWindow->SuperToLocal(theMouse);
  3311.                         aWindow->HandleMouseUp(theMouse, event, gStdHysteresis);
  3312.                     }
  3313. #if qDebug
  3314.                     else
  3315.                         ProgramBreak("In TApplication::HandleMouseUp: couldn't focus on a window object!");
  3316. #endif
  3317.                 }
  3318.                 else
  3319.                     this->HandleAlienEvent(event);
  3320.                 break;
  3321.             }
  3322.     }
  3323. } // TApplication::HandleMouseUp 
  3324.  
  3325. //----------------------------------------------------------------------------------------
  3326. // TApplication::HandleSystemEvent: 
  3327. //----------------------------------------------------------------------------------------
  3328. #pragma segment MAApplicationRes
  3329.  
  3330. void TApplication::HandleSystemEvent(TToolboxEvent* event)
  3331. {
  3332.     switch (((unsigned long)(event->fEventRecord.message & osEvtMessageMask)) >> 24)
  3333.     {
  3334.         case suspendResumeMessage:
  3335.             {
  3336.                 Boolean switchingIn = ((event->fEventRecord.message) & resumeFlag) != 0;
  3337.                 Boolean convertClipboard = ((event->fEventRecord.message) & convertClipboardFlag) != 0;
  3338.     
  3339.                 if (switchingIn)
  3340.                 {
  3341.                     // the Proces Manager may have activated the wrong window (if, when
  3342.                     // we suspended earlier, we had non-floating window(s) that hide on suspend
  3343.                     // such as the clipboard) so we augment what it did by activating the
  3344.                     // right one!
  3345.                     if (MAFrontWindow() != NULL)
  3346.                         MADeactivateWindow(MAFrontWindow());
  3347.                     
  3348.                     this->RegainControl(convertClipboard);
  3349.     
  3350.                     TWindow * aWindow = this->GetFrontWindow();
  3351.                     if (aWindow)
  3352.                         MAActivateWindow(aWindow->fWMgrWindow);
  3353.                 }
  3354.                 else
  3355.                 {
  3356.                     // When switching out, after having hid windows that get hid on suspend in
  3357.                     // AboutToLoseControl, we need to ensure that our idea about the front
  3358.                     // window and the Process Mgr's idea about the front window are the same.
  3359.                     // (note that we do the second half of the work when we get the resume
  3360.                     // event).
  3361.                     WindowPtr theFrontWindow = MAFrontWindow();// remember the front window
  3362.     
  3363.                     this->AboutToLoseControl(convertClipboard);// might hide windows…
  3364.     
  3365.                     TWindow * aWindow = this->GetActiveWindow(false);
  3366.                     if (aWindow)
  3367.                         MADeactivateWindow(aWindow->fWMgrWindow);
  3368.                 }
  3369.     
  3370.                 if (!(qNeedsProcessMgr || gConfiguration.hasProcessMgr))
  3371.                     fInBackground =!switchingIn;
  3372.     
  3373.                 this->InvalidateMouseRegions();
  3374.             }
  3375.             break;
  3376.  
  3377.         case mouseMovedMessage:
  3378.             event->fAffectsMenus = false;        // We don't think mouse tracking usually
  3379.                                                 // bothers the menus. We got the mouse
  3380.                                                 // moved event because the mouse strayed
  3381.                                                 // outside of fSleepRegion. It may or may
  3382.                                                 // not have strayed outside of the other
  3383.                                                 // mouse regions. We'll only invalidate
  3384.                                                 // them here (if necessary) because that
  3385.                                                 // way we can defer computing them for as
  3386.                                                 // long as possible.
  3387.             if (!PtInRgn(event->fEventRecord.where, fCursorRegion))
  3388.                 this->InvalidateCursorRgn();
  3389.             if (!PtInRgn(event->fEventRecord.where, fHelpRegion))
  3390.                 this->InvalidateHelpRgn();
  3391.             break;
  3392.  
  3393.         default:
  3394.             if (gIntenseDebugging)
  3395.                 fprintf(stderr, "in TApplication.HandleSystemEvent: got unrecognized event\n");
  3396.             break;
  3397.     }
  3398. } // TApplication::HandleSystemEvent 
  3399.  
  3400. //----------------------------------------------------------------------------------------
  3401. // TApplication::HandleToolboxEvent: 
  3402. //----------------------------------------------------------------------------------------
  3403. #pragma segment MAApplicationRes
  3404.  
  3405.  void TApplication::HandleToolboxEvent(TToolboxEvent* event)
  3406.  {
  3407.     FailInfo fi;
  3408.     Try(fi)
  3409.     {
  3410.         Boolean proceed = true;
  3411.     
  3412.         TBehavior* aBehavior = this->GetFirstEnabledBehavior();    
  3413.         if (aBehavior)
  3414.             proceed = !aBehavior->DoToolboxEvent(event);
  3415.     
  3416.         if (proceed)
  3417.             this->DoToolboxEvent(event);
  3418.  
  3419.         fi.Success();
  3420.     }
  3421.     else                                        // Recover
  3422.     {
  3423.         this->DidEvent(event);
  3424.         fi.ReSignal();
  3425.     }
  3426.  
  3427.     this->DidEvent(event);
  3428. } // TApplication::HandleToolboxEvent 
  3429.  
  3430. //----------------------------------------------------------------------------------------
  3431. // TApplication::HandleUpdateEvent: 
  3432. //----------------------------------------------------------------------------------------
  3433. #pragma segment MAApplicationRes
  3434.  
  3435. void TApplication::HandleUpdateEvent(TToolboxEvent* event)
  3436. {
  3437.     // We don't think that update events should affect menus.
  3438.     event->fAffectsMenus = false;
  3439.     
  3440.     TWindow * aWindow = this->WMgrToWindow((WindowPtr)event->fEventRecord.message);
  3441.     if (aWindow)
  3442.         aWindow->Update();
  3443.     else
  3444.         this->HandleAlienEvent(event);
  3445. } // TApplication::HandleUpdateEvent 
  3446.  
  3447. //----------------------------------------------------------------------------------------
  3448. // TApplication::Idle: 
  3449. //----------------------------------------------------------------------------------------
  3450. #pragma segment MAApplicationRes
  3451.  
  3452. void TApplication::Idle(IdlePhase phase)
  3453. {
  3454.     FailInfo fi;
  3455.     Try(fi)
  3456.     {
  3457.         if (phase == idleBegin)
  3458.         {
  3459.             if (!gInFilter && MemSpaceIsLow())
  3460.                 this->SpaceIsLowAlert();
  3461.             else
  3462.                 fNextSpaceMessage = TickCount();
  3463.         }
  3464.  
  3465.         // Create a new block for failure handling
  3466.         {
  3467.             CHandlerIterator iter(fHeadCohandler);
  3468.  
  3469.             for (TEventHandler * aHandler = iter.FirstHandler(); iter.More(); aHandler = iter.NextHandler())
  3470.                 aHandler->HandleIdle(phase);
  3471.         }
  3472.  
  3473. #if qDebug
  3474.         Assertion(this->GetTarget() != NULL, "GetTarget != NULL");
  3475. #endif
  3476.  
  3477.         // Create a new block for failure handling
  3478.         {
  3479.             CHandlerIterator iter(this->GetTarget());
  3480.  
  3481.             for (TEventHandler * aHandler = iter.FirstHandler(); iter.More(); aHandler = iter.NextHandler())
  3482.                 aHandler->HandleIdle(phase);
  3483.         }
  3484.  
  3485.         fi.Success();
  3486.     }
  3487.     else                                        // Recover
  3488.         {
  3489.             gInhibitNestedHandling = true;        // Don't want to come back into Idle From
  3490.             // alert filters or other strange places
  3491.             fi.ReSignal();
  3492.         }
  3493. } // TApplication::Idle 
  3494.  
  3495. //----------------------------------------------------------------------------------------
  3496. // TApplication::GetWaitTicks: 
  3497. //----------------------------------------------------------------------------------------
  3498. #pragma segment MAApplicationRes
  3499.  
  3500. long TApplication::GetWaitTicks(Boolean allowApplicationToSleep)
  3501. {
  3502.     const short kMaxSleep = 60;                    // max sleep in foreground so MultiFinder
  3503.     // gives time to non-desk accessory drivers
  3504.  
  3505.     long returnValue = 0;
  3506.  
  3507.     if (allowApplicationToSleep)
  3508.     {
  3509.         long compositeTicks = kMaxIdleTime;
  3510.  
  3511.         // Check the cohandler chain first.  Add new block for failure handling
  3512.         {
  3513.             CHandlerIterator iter(fHeadCohandler);
  3514.  
  3515.             for (TEventHandler * aHandler = iter.FirstHandler(); iter.More(); aHandler = iter.NextHandler())
  3516.                 compositeTicks = MinMax(0, aHandler->NextIdle() - TickCount(), compositeTicks);
  3517.         }
  3518.  
  3519. #if qDebug
  3520.         Assertion(this->GetTarget() != NULL, "GetTarget != NULL");
  3521. #endif
  3522.  
  3523.         // now run through the target chain.  Add new block for failure handling
  3524.         {
  3525.             CHandlerIterator iter(this->GetTarget());
  3526.  
  3527.             for (TEventHandler * aHandler = iter.FirstHandler(); iter.More(); aHandler = iter.NextHandler())
  3528.                 compositeTicks = MinMax(0, aHandler->NextIdle() - TickCount(), compositeTicks);
  3529.         }
  3530.  
  3531.         // faceless driver bug in M.F fixed in process manager 
  3532.         if (qNeedsProcessMgr || gConfiguration.hasProcessMgr)
  3533.             returnValue = compositeTicks;
  3534.         else if ((compositeTicks > kMaxSleep) && this->IsFrontProcess())
  3535.         {
  3536.             if (gIntenseDebugging && gReportEvent)
  3537.                 fprintf(stderr, "IN TApplication.GetWaitTicks: clipped to MaxSleep=%d\n", kMaxSleep);
  3538.             returnValue = Min(compositeTicks, kMaxSleep);
  3539.         }
  3540.     }
  3541.  
  3542.     return returnValue;
  3543. } // TApplication::GetWaitTicks 
  3544.  
  3545. //----------------------------------------------------------------------------------------
  3546. // TApplication::InModalState: 
  3547. //----------------------------------------------------------------------------------------
  3548. #pragma segment MAApplicationRes
  3549.  
  3550. Boolean TApplication::InModalState()
  3551. {
  3552.     WindowPtr aWindowPtr = FrontWindow();
  3553.  
  3554.     // in case the front window is an alert or something 
  3555.     if ((this->WMgrToWindow(aWindowPtr) == NULL) && (aWindowPtr))
  3556.         switch (GetWindowVariant(aWindowPtr))
  3557.         {
  3558.             case dBoxProc:
  3559.             case plainDBox:
  3560.             case altDBoxProc:
  3561.                 return true;
  3562.             default:
  3563.                 return false;
  3564.         }
  3565.     else
  3566.     {
  3567.         TWindow * aWindow = this->GetActiveWindow(kNoFloaters);
  3568.         return (aWindow && aWindow->IsInModalState());
  3569.     }
  3570. } // TApplication::InModalState 
  3571.  
  3572. //----------------------------------------------------------------------------------------
  3573. // TApplication::InstallCohandler: 
  3574. //----------------------------------------------------------------------------------------
  3575. #pragma segment MANonRes
  3576.  
  3577. void TApplication::InstallCohandler(TEventHandler* aCohandler,
  3578.                                     Boolean addIt)
  3579. {
  3580.     if (addIt)
  3581.         fHeadCohandler = aCohandler->AddHandler(fHeadCohandler);
  3582.     else
  3583.         fHeadCohandler = aCohandler->RemoveHandler(fHeadCohandler);
  3584. } // TApplication::InstallCohandler 
  3585.  
  3586. //----------------------------------------------------------------------------------------
  3587. // TApplication::IsDeskAccessory: 
  3588. //----------------------------------------------------------------------------------------
  3589. #pragma segment MAApplicationRes
  3590.  
  3591. Boolean TApplication::IsDeskAccessory(WindowPtr aWMgrWindow)
  3592. {
  3593.     return (!(qNeedsProcessMgr || gConfiguration.hasProcessMgr) && ((aWMgrWindow) && (((WindowPeek)aWMgrWindow)->windowKind < 0)));
  3594. } // TApplication::IsDeskAccessory 
  3595.  
  3596. //----------------------------------------------------------------------------------------
  3597. // TApplication::IsFrontProcess: 
  3598. //----------------------------------------------------------------------------------------
  3599. #pragma segment MAApplicationRes
  3600.  
  3601. Boolean TApplication::IsFrontProcess()
  3602. {
  3603.     if (qNeedsProcessMgr || gConfiguration.hasProcessMgr)
  3604.     {
  3605.         ProcessSerialNumber aPSN;
  3606.         ProcessSerialNumber applicationPSN;
  3607.         Boolean result;
  3608.  
  3609.         FailOSErr(GetFrontProcess(&aPSN));
  3610.         applicationPSN = fProcessNumber;
  3611.         FailOSErr(SameProcess(&aPSN, &applicationPSN, &result));
  3612.         return result;
  3613.     }
  3614.     else
  3615.         return !fInBackground;
  3616. } // TApplication::IsFrontProcess 
  3617.  
  3618. //----------------------------------------------------------------------------------------
  3619. // TApplication::MakeFrontProcess: 
  3620. //----------------------------------------------------------------------------------------
  3621. #pragma segment MAApplicationRes
  3622.  
  3623. void TApplication::MakeFrontProcess()
  3624. {
  3625.     if (!this->IsFrontProcess())
  3626.     {
  3627.         ProcessSerialNumber aPSN = fProcessNumber;
  3628.         FailOSErr(SetFrontProcess(&aPSN));
  3629.     }
  3630. } // TApplication::MakeFrontProcess 
  3631.  
  3632. //----------------------------------------------------------------------------------------
  3633. // TApplication::IsHelpEnabled: 
  3634. //----------------------------------------------------------------------------------------
  3635. #pragma segment MAApplicationRes
  3636.  
  3637. Boolean TApplication::IsHelpEnabled()
  3638. {
  3639.     if (qNeedsHelpMgr || gConfiguration.hasHelpMgr)
  3640.         return HMGetBalloons();
  3641.     else
  3642.         return false;
  3643. } // TApplication::IsHelpEnabled 
  3644.  
  3645. //----------------------------------------------------------------------------------------
  3646. // TApplication::InvalidateMouseRegions: 
  3647. //----------------------------------------------------------------------------------------
  3648. #pragma segment MAApplicationRes
  3649.  
  3650. void TApplication::InvalidateMouseRegions()
  3651. {
  3652.     this->InvalidateCursorRgn();
  3653.     this->InvalidateHelpRgn();
  3654. } // TApplication::InvalidateMouseRegions 
  3655.  
  3656. //----------------------------------------------------------------------------------------
  3657. // TApplication::InvalidateCursorRgn: 
  3658. //----------------------------------------------------------------------------------------
  3659. #pragma segment MAApplicationRes
  3660.  
  3661. void TApplication::InvalidateCursorRgn()
  3662. {
  3663.     if (fCursorRegion)
  3664.         SetEmptyRgn(fCursorRegion);                // Make sure it gets changed back 
  3665. } // TApplication::InvalidateCursorRgn 
  3666.  
  3667. //----------------------------------------------------------------------------------------
  3668. // TApplication::InvalidateHelpRgn: 
  3669. //----------------------------------------------------------------------------------------
  3670. #pragma segment MAApplicationRes
  3671.  
  3672. void TApplication::InvalidateHelpRgn()
  3673. {
  3674.     if (fHelpRegion)
  3675.         SetEmptyRgn(fHelpRegion);                // Make sure it gets changed back 
  3676.     if (qNeedsHelpMgr || gConfiguration.hasHelpMgr)
  3677.         if (this->IsFrontProcess() && HMIsBalloon())
  3678.         {
  3679.             OSErr err = HMRemoveBalloon();
  3680.             if (err != hmNoBalloonUp)
  3681.                 FailOSErr(err);
  3682.         }
  3683. } // TApplication::InvalidateHelpRgn 
  3684.  
  3685. //----------------------------------------------------------------------------------------
  3686. // TApplication::InvalidateFocus: 
  3687. //----------------------------------------------------------------------------------------
  3688. #pragma segment MAApplicationRes
  3689.  
  3690. void TApplication::InvalidateFocus()
  3691. {
  3692.     if (gFocusedView)
  3693.         gFocusedView->InvalidateFocus();
  3694. } // TApplication::InvalidateFocus 
  3695.  
  3696. //----------------------------------------------------------------------------------------
  3697. // TApplication::IsCursorRgnInvalid: 
  3698. //----------------------------------------------------------------------------------------
  3699. #pragma segment MAApplicationRes
  3700.  
  3701. Boolean TApplication::IsCursorRgnInvalid()
  3702. {
  3703.     // The cursor is normally tracked via MouseMoved events. But for those with special
  3704.     // needs fAlwaysTrackCursor can come to the rescue.
  3705.  
  3706.     return (EmptyRgn(fCursorRegion) || fAlwaysTrackCursor);
  3707. } // TApplication::IsCursorRgnInvalid 
  3708.  
  3709. //----------------------------------------------------------------------------------------
  3710. // TApplication::IsHelpRgnInvalid: 
  3711. //----------------------------------------------------------------------------------------
  3712. #pragma segment MAApplicationRes
  3713.  
  3714. Boolean TApplication::IsHelpRgnInvalid()
  3715. {
  3716.     return EmptyRgn(fHelpRegion);
  3717. } // TApplication::IsHelpRgnInvalid 
  3718.  
  3719. //----------------------------------------------------------------------------------------
  3720. // TApplication::KeyEventToComponents: 
  3721. //----------------------------------------------------------------------------------------
  3722. #pragma segment MAApplicationRes
  3723.  
  3724. void TApplication::KeyEventToComponents(TToolboxEvent* event)
  3725. // See Tech Note #263 for the reason for this abomination 
  3726. {
  3727.     const short kMaskModifier = 0xFE00;            // need to strip command key from Modifiers 
  3728.     const long kMaskASCII1 = 0x000000FF;        // get key from KeyTranslate return 
  3729.     const long kMaskASCII2 = 0x00FF0000;        // get key from KeyTranslate return 
  3730.     const short kUpKeyMask = 0x0080;
  3731.  
  3732.     Inherited::KeyEventToComponents(event);        // Get default translation, if any 
  3733.  
  3734.     if ((event->fEventRecord.what == keyDown) || (event->fEventRecord.what == keyUp) || (event->fEventRecord.what == autoKey))
  3735.     {
  3736.         // Now see if the command key is down. If it is, get the correct ASCII translation by
  3737.         // masking the command key out and re-translating because the command key will
  3738.         // mask the shift modifier.
  3739.  
  3740.         if (event->IsCommandKeyPressed())
  3741.         {
  3742.             // set the upkey bit so KeyTranslate doesn't do special deadkey processing
  3743.             // See IM-V pp. 195 
  3744.             short keyCodeParameter = ((((event->fEventRecord.modifiers) & kMaskModifier) | event->fKeyCode) | kUpKeyMask);
  3745.  
  3746.             long state = 0;
  3747.  
  3748.             // Get the correct keytable pointer. We don't want to grope the system unnecessarily so
  3749.             // use the script managers improvements if they're there.
  3750.             Ptr keyTransTable;
  3751.  
  3752. #if qPowerPC
  3753.             keyTransTable = (Ptr)(GetScriptManagerVariable(smKCHRCache));
  3754. #else
  3755.             if (qNeedsSystem7 || gConfiguration.systemVersion >= 0x700)
  3756.                 keyTransTable = (Ptr)(GetScriptManagerVariable(smKCHRCache));
  3757.             else
  3758.             {
  3759.                 // !!! Delete this record for 7.0 only operation. This is really a private record so
  3760.                 // _DON'T_ use any other fields!
  3761.  
  3762.                 struct MAExpandMemRec
  3763.                 {
  3764.                     short emVersion;            // version of expanded memory 
  3765.                     long emSize;                // length of em 
  3766.                     long emIntlGlobals;            // international globals pointer 
  3767.                     long emKeyDeadState;        // Key1Trans, Key2Trans dead state 
  3768.                     Ptr emKeyCache;                // KCHR keyboard cache 
  3769.                     long emInternationalDefinition;// Reserved for Intl 
  3770.                     Boolean emFirstKeyboard;    // flag byte 
  3771.                     Boolean emAlign;            // long-align until we need this storage 
  3772.                     long emItlCache[4];            // bytes in cache 
  3773.                     Boolean emItlNeedUnlock;    // for pack6 
  3774.                     Boolean emItlDirectGetIntl;    // for pack6 
  3775.                     unsigned char emFiller[22];    // Reserved room 
  3776.                 };
  3777.  
  3778.  
  3779.                 typedef struct MAExpandMemRec MAExpandMemRec;
  3780.                 typedef MAExpandMemRec* MAExpandMemRecPtr, ** MAExpandMemRecHandle;
  3781.  
  3782.                 // Fake handle.    the lomem address is a pointer to the table 
  3783.                 enum
  3784.                 {
  3785.                     ExpandMem = 0x2B6    // a holdover from SysEqu.h
  3786.                 };
  3787.                 keyTransTable = (Ptr)((*(MAExpandMemRecHandle)(ExpandMem))->emKeyCache);
  3788.             }
  3789. #endif
  3790.  
  3791.             long keyInfo = KeyTranslate(keyTransTable, keyCodeParameter, &state);
  3792.  
  3793.             event->fCharacter = (unsigned char)(((keyInfo) & kMaskASCII1));
  3794.             if (event->fCharacter == (unsigned char)(0))
  3795.                 event->fCharacter = (unsigned char)((keyInfo >> kMaskASCII2) & 16);
  3796.         }
  3797.     }
  3798. } // TApplication::KeyEventToComponents 
  3799.  
  3800. //----------------------------------------------------------------------------------------
  3801. // TApplication::KindOfDocument: 
  3802. //----------------------------------------------------------------------------------------
  3803. #pragma segment MAOpen
  3804.  
  3805. CommandNumber TApplication::KindOfDocument(CommandNumber itsCommandNumber,
  3806.                                                   TFile*)
  3807. {
  3808.     return itsCommandNumber;
  3809. } // TApplication::KindOfDocument 
  3810.  
  3811. //----------------------------------------------------------------------------------------
  3812. // TApplication::MainEventLoop: 
  3813. //----------------------------------------------------------------------------------------
  3814. #pragma segment MAApplicationRes
  3815. // must be in the main segment 
  3816.  
  3817. void TApplication::MainEventLoop()
  3818. {
  3819.     fIdlePhase = idleBegin;
  3820.     while (!fDone)
  3821.         this->PollEvent(kAllowApplicationToSleep);
  3822. } // TApplication::MainEventLoop 
  3823.  
  3824. //----------------------------------------------------------------------------------------
  3825. // TApplication::DoLaunchClipboard: 
  3826. //----------------------------------------------------------------------------------------
  3827. #pragma segment MAOpen
  3828.  
  3829. void TApplication::DoLaunchClipboard()
  3830. {
  3831.     if (gClipboardMgr)
  3832.     {
  3833.         gClipboardMgr->Launch();                // Launch after segments are unloaded
  3834.                                                 // since reading the scrap may be piggy
  3835.     }
  3836. } // TApplication::DoLaunchClipboard 
  3837.  
  3838. //----------------------------------------------------------------------------------------
  3839. // TApplication::MakeViewForAlienClipboard: 
  3840. //----------------------------------------------------------------------------------------
  3841. #pragma segment MAClipboard
  3842.  
  3843. TView* TApplication::MakeViewForAlienClipboard()
  3844. {
  3845.     return NULL;                                // use defaults 
  3846. } // TApplication::MakeViewForAlienClipboard 
  3847.  
  3848. //----------------------------------------------------------------------------------------
  3849. // TApplication::MenuEvent: 
  3850. //----------------------------------------------------------------------------------------
  3851. #pragma segment MASelCommand
  3852.  
  3853. void TApplication::MenuEvent(long menuItem)
  3854. {
  3855.     short theMenuNumber = HiWord(menuItem);
  3856.     short theItemNumber = LoWord(menuItem);
  3857.  
  3858.     if (theMenuNumber)
  3859.     {
  3860.         CommandNumber command = CommandFromMenuItem(theMenuNumber, theItemNumber);
  3861.         VOLATILE(command);
  3862.  
  3863. #if qDebugMsg
  3864.         if (command == cCantUndo)
  3865.         {
  3866.             fprintf(stderr, "Command number %d is reserved for MacApp.\n", cCantUndo);
  3867.             ProgramBreak("Use of reserved command number.");
  3868.         }
  3869.  
  3870.         if (gReportMenuChoices && (command > 0))
  3871.             fprintf(stderr, "Menu Choice Command Number == %d\n", command);
  3872. #endif
  3873.  
  3874.         if ((command < 0) && (theMenuNumber == mApple))
  3875.         {
  3876.             CStr255 deskAccName;
  3877.  
  3878.             GetMenuItemText(MAGetMenuHandle(mApple), theItemNumber, deskAccName);
  3879.             this->OpenDeskAccessory(deskAccName);
  3880.         }
  3881.         else if ((command < cEditBase) || (command > cEditLast) || (!SystemEdit((short)(command - cEditBase))))
  3882.         {
  3883.             FailInfo fi;
  3884.             Try(fi)
  3885.             {
  3886.                 if (fSysWindowActive)
  3887.                     this->ActivateBusyCursor(true);
  3888.  
  3889.                 this->GetTarget()->HandleMenuCommand(command);
  3890.  
  3891.                 if (fSysWindowActive)
  3892.                     this->ActivateBusyCursor(false);
  3893.                 fi.Success();
  3894.             }
  3895.             else                                // Recover
  3896.                 {
  3897.                     if (fSysWindowActive)
  3898.                         this->ActivateBusyCursor(false);
  3899.  
  3900.                     FailNewMessage(fi.error, fi.message, BuildMessage((short)command, messageCommandError));
  3901.                     fi.ReSignal();
  3902.                 }
  3903.         }
  3904.     }
  3905. } // TApplication::MenuEvent 
  3906.  
  3907. //----------------------------------------------------------------------------------------
  3908. // TApplication::OpenDeskAccessory: 
  3909. //----------------------------------------------------------------------------------------
  3910. void TApplication::OpenDeskAccessory(const CStr255& deskAccName)
  3911. {
  3912. #if !qPowerPC
  3913.     // then go ahead and open it; it's in a separate process
  3914.     if (qNeedsProcessMgr || gConfiguration.hasProcessMgr)
  3915.     {
  3916. #endif
  3917.         GrafPtr savedPort;
  3918.  
  3919.         GetPort(&savedPort);
  3920.         OpenDeskAcc(deskAccName);
  3921.         SetPort(savedPort);
  3922. #if !qPowerPC
  3923.     }
  3924.     else
  3925.     {
  3926.         GrafPtr savedPort;
  3927.  
  3928.         Boolean oldPerm;
  3929.         Boolean ourHeap;
  3930.         Handle drvrH;
  3931.         ResType theType;
  3932.         short theID;
  3933.         Str255 theName;
  3934.  
  3935.         short aRefNum;
  3936.         VOLATILE(aRefNum);
  3937.  
  3938.         FailInfo fi;
  3939.         Try(fi)
  3940.         {
  3941.             aRefNum = 0;                        // Make sure failure handler works. 
  3942.  
  3943.             // Attempt to load the DA into memory. If 'deskAccName' refers to another app
  3944.             // rather than a real desk acc, then GetNamedResource returns a faked up
  3945.             // handle courtesy of MultiFinder . We open the DA with permanent allocation
  3946.             // so as to ensure that we don't take space from our code segments.
  3947.  
  3948.             oldPerm = PermAllocation(true);
  3949.             drvrH = GetNamedResource('DRVR', deskAccName);
  3950.             PermAllocation(oldPerm);
  3951.             FailNILResource(drvrH);                // Either there wasn't enough memory to
  3952.                                                 // load the DA, or something is seriously
  3953.                                                 // wrong.
  3954.  
  3955.             // At this point if we are really opening a DA we know it fits in memory.  
  3956.  
  3957.             GetResInfo(drvrH, &theID, &theType, theName);// If it's a not a real DA then this 
  3958.             // will generate a ResError.   
  3959.  
  3960.             // Find out which zone it lives in, or if option key is down.
  3961.             ourHeap = ((HandleZone(drvrH) == ApplicationZone()) || (this->IsFrontProcess() && IsOptionKeyDown()));
  3962.  
  3963.             if ((ResError() != noErr) ||        // If it's a MultiFinder fake DA, 
  3964.                 IsOpen(theID) ||                // …or if the DA is already open, 
  3965.                 (!ourHeap))                        // …or if it's not going in our heap 
  3966.             {
  3967.                 oldPerm = PermAllocation(true);    // In case we guess wrong 
  3968.                 GetPort(&savedPort);
  3969.                 aRefNum = OpenDeskAcc(deskAccName);// …then go ahead and open it. 
  3970.                 SetPort(savedPort);
  3971.                 PermAllocation(oldPerm);
  3972.             }
  3973.             else
  3974.             {
  3975.                 // If we get this far, we know we have a real DA and it's going into our
  3976.                 // heap. Open it, but them make sure we have enough memory to continue
  3977.                 // running.
  3978.  
  3979.                 FailSpaceIsLow();                // In case we're already low on mem. 
  3980.  
  3981.                 oldPerm = PermAllocation(true);    // If the pig wants to wallow 
  3982.                 GetPort(&savedPort);
  3983.                 aRefNum = OpenDeskAcc(deskAccName);// Use temporary allocation. 
  3984.                 SetPort(savedPort);
  3985.                 PermAllocation(oldPerm);
  3986.  
  3987.                 FailSpaceIsLow();                // Fail if not enough memory left. 
  3988.                 FailNIL(*drvrH);                // …or if the driver was purged to 
  3989.                 // …satisfy a code space requirement.
  3990.             }
  3991.             fi.Success();
  3992.         }
  3993.         else                                    // Recover
  3994.             {
  3995.                 if (aRefNum)
  3996.                     CloseDeskAcc(aRefNum);
  3997.  
  3998.                 if (fi.message == 0)
  3999.                 {
  4000.                     gErrorParm3 = deskAccName;
  4001.                     // Get rid of leading NULL character 
  4002.                     if (gErrorParm3[1] == 0)
  4003.                         gErrorParm3.Delete(1, 1);
  4004.                 }
  4005.  
  4006.                 FailNewMessage(fi.error, fi.message, messageOpenFailed);
  4007.                 fi.ReSignal();
  4008.             }
  4009.     }
  4010. #endif
  4011. } // TApplication::OpenDeskAccessory 
  4012.  
  4013. //----------------------------------------------------------------------------------------
  4014. // TApplication::OpenNew: 
  4015. //----------------------------------------------------------------------------------------
  4016. #pragma segment MAOpen
  4017.  
  4018. TDocument* TApplication::OpenNew(CommandNumber itsCommandNumber)
  4019. {
  4020.     TDocument* aDocument = NULL;
  4021.     VOLATILE(aDocument);
  4022.  
  4023.     FailInfo fi;
  4024.     Try(fi)
  4025.     {
  4026.         FailNIL(aDocument = this->DoMakeDocument(this->KindOfDocument(itsCommandNumber, NULL), NULL));
  4027.         aDocument->DoInitialState();
  4028.  
  4029.         aDocument->DoMakeViews(kForDisplay);
  4030.  
  4031.         CStr255 newTitle;
  4032.         aDocument->UntitledName(newTitle);
  4033.         aDocument->SetTitle(newTitle);
  4034.  
  4035.         FailSpaceIsLow();                        // Fail if document leaves us with no room 
  4036.  
  4037.         // Don't attempt to show the windows until we're sure we won't fail 
  4038.         aDocument->DoPostMakeViews(kForDisplay);
  4039.  
  4040.         fi.Success();
  4041.     }
  4042.     else                                        // Recover
  4043.     {
  4044.         if (aDocument)
  4045.             aDocument = (TDocument *)(FreeIfObject(aDocument));    // The document will free the file
  4046.  
  4047.         FailNewMessage(fi.error, fi.message, messageNewFailed);
  4048.         fi.ReSignal();
  4049.     }
  4050.     return aDocument;
  4051. } // TApplication::OpenNew 
  4052.  
  4053. //----------------------------------------------------------------------------------------
  4054. // TApplication::OpenOld: 
  4055. //----------------------------------------------------------------------------------------
  4056. #pragma segment MAOpen
  4057.  
  4058. TDocument* TApplication::OpenOld(CommandNumber itsOpenCommand, TList* aFileList)
  4059. {
  4060.     TDocument* aDocument = NULL;
  4061.     TFile* aFile = NULL;
  4062.     TFile* aNewFile = NULL;
  4063.     
  4064.     Size oldCodeReserve;
  4065.     Size oldMemReserve;
  4066.  
  4067.     OSErr savedError = 0;
  4068.     long  savedMessage = 0;
  4069.  
  4070.     VOLATILE(aDocument);
  4071.     VOLATILE(aFile);
  4072.     VOLATILE(aNewFile);
  4073.     VOLATILE(oldCodeReserve);
  4074.     VOLATILE(oldMemReserve);
  4075.     VOLATILE(savedError);
  4076.     VOLATILE(savedMessage);
  4077.  
  4078.   {    // Put iterator in a separate block so that it will go out of scope before the end of the method.
  4079.     // We don't want the iterator's failure handler to be invoked, because its stack ptr is munged.
  4080.     // If an error occurs, we'll just save it and ReSignal it after the iterator is gone.
  4081.  
  4082.     CObjectIterator iter(aFileList);
  4083.     for (aFile = (TFile *)iter.FirstObject(); iter.More() && !savedError; aFile = (TFile *)iter.NextObject())
  4084.     {
  4085.         // reset aDocument and aNewFile so that they no longer refer to items from the
  4086.         // last go round (important in case we fail downstream)…
  4087.         aDocument = NULL;
  4088.         aNewFile = NULL;
  4089.         
  4090.         CStr63 fileName;
  4091.         aFile->GetName(fileName);            // If failure occurs the file may already be
  4092.                                             // freed so we will save the name just in
  4093.                                             // case.
  4094.         
  4095.         aFileList->Delete(aFile);            // ReadStationery if successful will dispose
  4096.                                             // of the file for us so if failure occurs
  4097.                                             // this had better not be in the file list.
  4098.         
  4099.         FailInfo fi;
  4100.         Try(fi)
  4101.         {
  4102.             // Set reserve down a little to ensure that we can open existing documents 
  4103.             GetReserveSize(oldCodeReserve, oldMemReserve);
  4104.             SetReserveSize(oldCodeReserve, oldMemReserve / 2);
  4105.             
  4106.             TDocument * otherDoc = this->FindDocument(aFile);
  4107.             Boolean isStationery = aFile->IsStationery();
  4108.             
  4109.             if (otherDoc && !isStationery)
  4110.             {
  4111.                 otherDoc->OpenAgain(itsOpenCommand, aDocument);
  4112.                 aFile = (TFile*)FreeIfObject(aFile);
  4113.                 SetReserveSize(oldCodeReserve, oldMemReserve);
  4114.             }
  4115.             else if (this->CanOpenDocument(itsOpenCommand, aFile))
  4116.             {
  4117.                 TFile* fileOwnedByDoc = aFile;
  4118.                 aFile = NULL;
  4119.                 FailNIL(aDocument = this->DoMakeDocument(this->KindOfDocument(itsOpenCommand, fileOwnedByDoc), fileOwnedByDoc));
  4120.  
  4121.                 if (!isStationery)
  4122.                     aDocument->ReadDocument(kForDisplay);
  4123.                 else
  4124.                 {
  4125.                     aNewFile = this->DoMakeFile(itsOpenCommand);
  4126.                     aDocument->ReadStationery(aNewFile);
  4127.                     aFile = NULL;                // This file has already been freed by ReadStationery.
  4128.                     aNewFile = NULL;            // Clear our reference so that if we fail
  4129.                                                 // we don't try to free this file twice.
  4130.                 }
  4131.                 
  4132.                 aDocument->DoMakeViews(kForDisplay);
  4133.                 
  4134.                 if (isStationery)
  4135.                 {
  4136.                     CStr255 newTitle;
  4137.                     aDocument->UntitledName(newTitle);
  4138.                     aDocument->SetTitle(newTitle);
  4139.                 }
  4140.     
  4141.                 FailSpaceIsLow();                // Fail if the document leaves us with no
  4142.                                                 // memory
  4143.                 // Set the reserve back to where it was 
  4144.                 SetReserveSize(oldCodeReserve, oldMemReserve);
  4145.     
  4146.                 // Don't attempt to show the windows until we're sure we won't fail 
  4147.                 aDocument->DoPostMakeViews(kForDisplay);
  4148.             }
  4149.             else
  4150.                 Failure(errNotMyType, 0);
  4151.             fi.Success();
  4152.         }
  4153.         else // Recover
  4154.         {
  4155.             if (fi.message == 0)
  4156.                 gErrorParm3 = fileName;
  4157.                 
  4158.             // ok, this gets tricky but here is how it works. If we have a document then
  4159.             // we know that we failed after DoMakeDocument and aFile will be freed by
  4160.             // freeing the document or it has already been freed as a side effect of
  4161.             // reading the stationery. If we don't have a document then we need to free
  4162.             // aFile ourselves.
  4163.             if (aDocument)
  4164.                 aDocument = (TDocument *)(FreeIfObject(aDocument));    // The document will free the file
  4165.             else
  4166.                 aFile = (TFile*)FreeIfObject(aFile);                // otherwise its our responsibility
  4167.                 
  4168.             aNewFile = (TFile*)FreeIfObject(aNewFile);                // If we successfully read the
  4169.                                                                     // stationery then aNewFile will be NULL
  4170.             
  4171.             // Set the reserve back to where it was 
  4172.             SetReserveSize(oldCodeReserve, oldMemReserve);
  4173.             
  4174.             //    Don't want to fail here, because the CObjectIterator (with its embedded FailInfo) is 
  4175.             //    still in scope. Instead, save the error info until after the iterator has self-destructed.
  4176.             //    FailNewMessage(fi.error, fi.message, messageOpenFailed);
  4177.             savedError = fi.error;
  4178.             savedMessage = fi.message;
  4179.             if (!savedMessage)
  4180.                 savedMessage = messageOpenFailed;
  4181.         }
  4182.     }
  4183.   } // iterator will self-destruct now
  4184.  
  4185.       if (savedError != noErr)                        // Do we need to ReSignal a failure?
  4186.     {
  4187.         // signal the failure
  4188.         Failure(savedError, savedMessage);
  4189.     }
  4190.     return aDocument;
  4191. } // TApplication::OpenOld 
  4192.  
  4193. //----------------------------------------------------------------------------------------
  4194. // TApplication::ProcessEvent: 
  4195. //----------------------------------------------------------------------------------------
  4196. #pragma segment MAApplicationRes
  4197.  
  4198. void TApplication::ProcessEvent(TEvent* event)
  4199. {
  4200.     if (qDebug &&!event)
  4201.         ProgramBreak("NULL passed to TApplication::ProcessEvent");
  4202.     else if (qDebug && (!IsObject(event)))        // since it's possible to have passed in a
  4203.                                                 // freed undoable command allocated in a
  4204.                                                 // global variable (due to pilot error)
  4205.     {
  4206.         VerboseIsObject(event);
  4207.         ProgramBreak("bogus object passed to TApplication::ProcessEvent");
  4208.     }
  4209.     else
  4210.     {
  4211. #if qDebug
  4212.         if (gIntenseDebugging)
  4213.         {
  4214.             MAName aMAName;
  4215.             event->GetClassName(aMAName);
  4216.             fprintf(stderr, "The Event to process: %s\n", (char*)aMAName);
  4217.         }
  4218. #endif
  4219.  
  4220.     }
  4221.     if (event)
  4222.         event->Process();
  4223. } // TApplication::ProcessEvent 
  4224.  
  4225.  
  4226. //----------------------------------------------------------------------------------------
  4227. // TApplication::PollEvent: 
  4228. //----------------------------------------------------------------------------------------
  4229. #pragma segment MAApplicationRes
  4230.  
  4231. void TApplication::PollEvent(Boolean allowApplicationToSleep)
  4232. {
  4233.     Boolean didAllowApplicationToSleep = fAllowApplicationToSleep;
  4234.  
  4235.     VOLATILE(didAllowApplicationToSleep);
  4236.  
  4237.     fAllowApplicationToSleep = allowApplicationToSleep;
  4238.  
  4239.     ++fEventLevel;
  4240.  
  4241. #if qDebugMsg
  4242.     if (!this->GetTarget())
  4243.         ProgramBreak("Serious Error!! in TApplication.PollEvent: target == NULL");
  4244. #endif
  4245.  
  4246.     FailInfo fi;
  4247.     Try(fi)
  4248.     {
  4249.         TEvent * retrievedEvent = this->RetrieveAnEvent();
  4250.         if (retrievedEvent)
  4251.             this->ProcessEvent(retrievedEvent);
  4252.  
  4253.         // The desk scrap may have been changed by use of command-X or command-C in desk accessories.
  4254.         if (fSysWindowActive)
  4255.         {
  4256.             gClipboardMgr->CheckDeskScrap();
  4257.             this->InvalidateFocus();
  4258.         }
  4259.  
  4260.         fi.Success();
  4261.         --fEventLevel;
  4262.  
  4263.         if (fEventLevel == 0)
  4264.             gInhibitNestedHandling = false;        // All clear 
  4265.     }
  4266.     else                                        // Recover
  4267.         {
  4268. #if qDebugMsg
  4269.             fprintf(stderr, "\n");                // add a blank line after all the messages from Failure
  4270. #endif
  4271.  
  4272.             fAllowApplicationToSleep = didAllowApplicationToSleep;
  4273.  
  4274.             --fEventLevel;
  4275.             if (fEventLevel == 0)
  4276.             {
  4277.                 if (fi.error != noErr)
  4278.                 {
  4279. #if !qPowerPC
  4280.                     UnloadAllSegments();
  4281. #endif
  4282.                     this->ShowError(fi.error, fi.message);
  4283.                 }
  4284.  
  4285.                 InvalidateMenus();
  4286.             }
  4287.             else
  4288.                 fi.ReSignal();
  4289.         }
  4290.  
  4291.     fAllowApplicationToSleep = didAllowApplicationToSleep;
  4292. } // TApplication::PollEvent 
  4293.  
  4294. //----------------------------------------------------------------------------------------
  4295. // TApplication::PollToolboxEvent: 
  4296. //----------------------------------------------------------------------------------------
  4297. #pragma segment MAApplicationRes
  4298.  
  4299. Boolean TApplication::PollToolboxEvent(Boolean allowApplicationToSleep)
  4300. {
  4301.     long waitTicks = 0;
  4302.     RgnHandle sleepRegion = NULL;
  4303.  
  4304.     EventRecord theEvent;
  4305.     if (!EventAvail(fMainEventMask, &theEvent))    // We'll only sleep if there aren't any
  4306.                                                 // waiting Events (keystrokes, mousedowns)
  4307.     {
  4308.         this->SetupTheMenus();
  4309.  
  4310.         // ensure that an event didn't come in during SetupTheMenus
  4311.         if (!EventAvail(fMainEventMask, &theEvent))
  4312.         {
  4313.             sleepRegion = this->GetSleepRegion();
  4314.  
  4315.             // ensure that an event didn't come in during GetSleepRegion
  4316.             if (!EventAvail(fMainEventMask, &theEvent))
  4317.                 waitTicks = this->GetWaitTicks(allowApplicationToSleep);// calc last so it's most accurate 
  4318.             else
  4319.                 sleepRegion = NULL;
  4320.         }
  4321.     }
  4322.  
  4323.     HiliteMenu(0);                                // Cleanup any menu titles left hilited.
  4324.                                                 // Done here so titles stay hilited until
  4325.                                                 // synchronous actions are performed.
  4326.     TToolboxEvent * event = this->GetEvent(fMainEventMask, waitTicks, sleepRegion);
  4327.     Boolean gotAnEvent = (event != NULL);
  4328.     if (gotAnEvent)
  4329.     {
  4330.         // GetEvent returned an event (work to do). If we were idling before then we must
  4331.         // keep the calls balanced with an IdleEnd to because we are no longer idling
  4332.         if (fIdlePhase == idleContinue)
  4333.         {
  4334.             this->Idle(idleEnd);
  4335.             fIdlePhase = idleBegin;
  4336.         }
  4337.         
  4338.         // Rather than posting the event where it would have to be sorted and compete with
  4339.         // other commands we will process the command directly.
  4340.         this->ProcessEvent(event);
  4341.  
  4342.         // The desk scrap may have been changed by use of command-X or command-C in desk accessories.
  4343.         if (fSysWindowActive)
  4344.         {
  4345.             gClipboardMgr->CheckDeskScrap();
  4346.             this->InvalidateFocus();
  4347.         }
  4348.     }
  4349.     else                                        // Woke up with no event available. Truly idle
  4350.         {
  4351.             this->Idle(fIdlePhase);
  4352.             fIdlePhase = idleContinue;
  4353.         }
  4354.  
  4355. #if qDebug
  4356.     gErrorParm3 = "?????";                        // to prevent anyone from using old values 
  4357. #endif
  4358.  
  4359.     return gotAnEvent;
  4360. } // TApplication::PollToolboxEvent 
  4361.  
  4362. //----------------------------------------------------------------------------------------
  4363. // TApplication::PostAnEvent: 
  4364. //----------------------------------------------------------------------------------------
  4365. #pragma segment MAApplicationRes
  4366.  
  4367. void TApplication::PostAnEvent(TEvent* event)    // Override
  4368. {
  4369.     FailInfo fi;
  4370.     
  4371.     Try(fi)
  4372.     {
  4373.         if (event->IsReadyToPost())
  4374.             fEventList->Insert(event);        // inserts event ordered the list
  4375.         
  4376.         fi.Success();
  4377.     }
  4378.     else
  4379.     {
  4380.         if (event->ShouldFreeOnCompletion())
  4381.             event = (TEvent *)FreeIfObject(event);
  4382.         fi.ReSignal();
  4383.     }
  4384. } // TApplication::PostAnEvent 
  4385.  
  4386. //----------------------------------------------------------------------------------------
  4387. // TApplication::PostCommand: 
  4388. //----------------------------------------------------------------------------------------
  4389. #pragma segment MAApplicationRes
  4390.  
  4391. void TApplication::PostCommand(TCommand* command)// Override
  4392. {
  4393.     if (command)
  4394.         this->PostAnEvent(command);
  4395. } // TApplication::PostCommand 
  4396.  
  4397. //----------------------------------------------------------------------------------------
  4398. // TApplication::PostPendingReplyCommand: 
  4399. //----------------------------------------------------------------------------------------
  4400. #pragma segment MAApplicationRes
  4401.  
  4402. void TApplication::PostPendingReplyCommand(TCommand* command)
  4403. {
  4404.     fPendingReplyList->Insert(command);
  4405. } // TApplication::PostPendingReplyCommand 
  4406.  
  4407. //----------------------------------------------------------------------------------------
  4408. // TApplication::DidEvent: 
  4409. //----------------------------------------------------------------------------------------
  4410. #pragma segment MAApplicationRes
  4411.  
  4412. void TApplication::DidEvent(TToolboxEvent* event)
  4413. {
  4414.     if (event && event->fAffectsMenus)
  4415.         InvalidateMenus();
  4416.  
  4417.     Boolean perm = PermAllocation(false);
  4418. #if qDebug
  4419.     if (perm)
  4420.         ProgramBreak("The permanent flag was left true.");
  4421. #endif
  4422.  
  4423.     // See if a system window has been activated or deactivated. 
  4424.     if (!(qNeedsProcessMgr || gConfiguration.hasProcessMgr) && (fSysWindowActive != this->IsDeskAccessory(FrontWindow())))
  4425.     {
  4426.         fSysWindowActive =!fSysWindowActive;
  4427.  
  4428.         if (fSysWindowActive)                    // deactivating to sys window 
  4429.         {
  4430.             this->AboutToLoseControl(true);
  4431.             InvalidateMenuBar();
  4432.         }
  4433.         else                                    // coming back from sys window 
  4434.             this->RegainControl(true);
  4435.     }
  4436.  
  4437.     if (event && (event->ShouldFreeOnCompletion()))
  4438.         event = (TToolboxEvent *)FreeIfObject(event);
  4439. } // TApplication::DidEvent 
  4440.  
  4441. //----------------------------------------------------------------------------------------
  4442. // TApplication::PrintDocuments: 
  4443. //----------------------------------------------------------------------------------------
  4444. #pragma segment MAFinder
  4445.  
  4446. void TApplication::PrintDocuments(TList* aFileList)
  4447. {
  4448.     TDocument* aDocument = NULL;
  4449.     TFile* aFile = NULL;
  4450.     
  4451.     VOLATILE(aDocument);
  4452.     VOLATILE(aFile);
  4453.  
  4454.     gFinderPrintingProceed = true;            // set in TStdPrintHandler::DoPrintCommand
  4455.     
  4456.     // If we have previously done a finder print we need to toss the old print information
  4457.     // or we won't ask the user for some new stuff.
  4458.     gFinderHPrint = DisposeIfHandle(gFinderHPrint);
  4459.  
  4460.     CObjectIterator iter(aFileList);
  4461.     for (aFile = (TFile *)iter.FirstObject(); iter.More(); aFile = (TFile *)iter.NextObject())
  4462.     {
  4463.         if (gFinderPrintingProceed)
  4464.         {
  4465.             FailInfo fi;
  4466.             Try(fi)
  4467.             {
  4468.                 FailNIL(aDocument = this->DoMakeDocument(this->KindOfDocument(cFinderPrint, aFile), aFile));
  4469.                 aDocument->ReadDocument(kForPrinting);
  4470.                 aDocument->DoMakeViews(kForPrinting);
  4471.                 aDocument->DoPostMakeViews(kForPrinting);
  4472.  
  4473.                 aDocument->HandleMenuCommand(cFinderPrint);
  4474.  
  4475.                 fi.Success();
  4476.             }
  4477.             else                                // Recover
  4478.             {
  4479.                 if (aDocument)
  4480.                 {
  4481.                     // If there is a document then it will have a reference to aFile and
  4482.                     // will free it when it is freed. Therefore we need to remove it from
  4483.                     // the list so that when the file list is freed we don't attempt to
  4484.                     // free it twice.
  4485.                     aFileList->Delete(aFile);
  4486.                     aDocument = (TDocument *)FreeIfObject(aDocument);
  4487.                 }
  4488.                 fi.ReSignal();
  4489.             }
  4490.             aFileList->Delete(aFile);
  4491.             aDocument = (TDocument *)FreeIfObject(aDocument);
  4492.         }
  4493.         else
  4494.             break;                                // The user canceled printing
  4495.     }
  4496. } // TApplication::PrintDocuments 
  4497.  
  4498. //----------------------------------------------------------------------------------------
  4499. // TApplication::RegainControl: 
  4500. //----------------------------------------------------------------------------------------
  4501. #pragma segment MAApplicationRes
  4502.  
  4503. void TApplication::RegainControl(Boolean checkClipboard)
  4504. {
  4505. #if qNeedsVU
  4506.     Inherited::RegainControl(checkClipboard);
  4507. #endif
  4508.  
  4509.     this->ActivateBusyCursor(true);
  4510.  
  4511.     gClipboardMgr->RegainControl(checkClipboard);
  4512.  
  4513.     // Let all windows know that we're regaining control - e.g. so floaters can show themselves 
  4514.     CWMgrIterator iter;
  4515.     for (WindowPtr aWinPtr = iter.FirstWMgrWindow(); iter.More(); aWinPtr = iter.NextWMgrWindow())
  4516.     {
  4517.         TWindow * aWindow = this->WMgrToWindow(aWinPtr);
  4518.  
  4519.         if (aWindow)
  4520.             aWindow->RegainControl();
  4521.     }
  4522. } // TApplication::RegainControl 
  4523.  
  4524. //----------------------------------------------------------------------------------------
  4525. // TApplication::Run: 
  4526. //----------------------------------------------------------------------------------------
  4527. #pragma segment MAApplicationRes
  4528. // must be in the main segment 
  4529.  
  4530. void TApplication::Run()
  4531. {
  4532. #if !qPowerPC
  4533.     UnloadAllSegments();
  4534. #endif
  4535.     FailSpaceIsLow();                    // make sure we have enough memory to continue
  4536.     gInitialized = true;                // was set false at static init time 
  4537.  
  4538.     this->DoLaunchClipboard();
  4539.  
  4540.     // I know this looks funny but this does cover the case where we are built for system
  4541.     // 6.0 but are running on system 7.0. In that case we still don't want to
  4542.     // HandleFinderRequest. However if we are built for system 7.0 then this code will be
  4543.     // conditionally compiled out
  4544.     if (!gConfiguration.hasAppleEventMgr)
  4545.     {
  4546. #if !qPowerPC
  4547.         UnloadAllSegments();
  4548. #endif
  4549.         this->HandleFinderRequest();
  4550.     }
  4551.  
  4552. #if !qPowerPC
  4553.     UnloadAllSegments();
  4554. #endif
  4555.     fEventLevel = 0;                            // Indicate outermost level 
  4556.     this->MainEventLoop();                        // runs until a quit command 
  4557.  
  4558.     this->AboutToLoseControl(true);
  4559.  
  4560. #if qDebug
  4561.     // See if previous max. resource usage has been exceeded by the termination code and
  4562.     // resources.
  4563.     CheckRsrcUsage();
  4564.  
  4565.     // We must call CleanupMacApp here; if we wait to fall thru to the end of the main
  4566.     // program, A5 has been invalidated and we can't refer to any globals.
  4567.     CleanupMacApp();
  4568. #endif
  4569. } // TApplication::Run 
  4570.  
  4571. //----------------------------------------------------------------------------------------
  4572. // TApplication::SelectToolboxWindow: 
  4573. //----------------------------------------------------------------------------------------
  4574. #pragma segment MAApplicationRes
  4575.  
  4576. void TApplication::SelectToolboxWindow(WindowPtr windowToSelect)
  4577. {
  4578.     WindowPtr currentFrontWindow = NULL;
  4579.     WindowPtr lastFloatingWindow = NULL;
  4580.     Boolean isFloatingWindow = IsFloatWindow(windowToSelect);
  4581.  
  4582.     if (isFloatingWindow)
  4583.     {
  4584.         currentFrontWindow = GetFirstFloatingWindowPtr();
  4585.     }
  4586.     else
  4587.     {
  4588.         currentFrontWindow = MAFrontWindow();
  4589.         lastFloatingWindow = GetLastFloatingWindowPtr();
  4590.     }
  4591.  
  4592.     // Be fast (and lazy) and do nothing if we don’t have to.
  4593.     if (currentFrontWindow != windowToSelect)
  4594.     {
  4595.         // Selecting floating windows are easy, since they’re always active
  4596.         if (isFloatingWindow)
  4597.             BringToFront(windowToSelect);
  4598.         else
  4599.         {
  4600.             // If there are no floating windows, we can call SelectWindow like the good ol’ days
  4601.             if (lastFloatingWindow == NULL)
  4602.                 SelectWindow(windowToSelect);
  4603.             else
  4604.             {
  4605.                 // Deactivate the window currently in front.
  4606.                 MADeactivateWindow(currentFrontWindow);
  4607.     
  4608.                 // Bring it behind the last floating window if it is not modal and activate it.
  4609.                 // Note that Inside Mac 1 states that you need to call PaintOne() and CalcVis() on a
  4610.                 // window if you are using SendBehind() to bring it closer to the front.  With System 7,
  4611.                 // this is no longer necessary.
  4612.                 
  4613.                 if (!(IsModalWindow(windowToSelect)))
  4614.                     SendBehind(windowToSelect,lastFloatingWindow);
  4615.                 else
  4616.                     BringToFront(windowToSelect);
  4617.                 
  4618.                 MAActivateWindow(windowToSelect);
  4619.             }
  4620.         }
  4621.     }
  4622.  
  4623.     // Make sure previous mouse clicks are not considered part of a multi-click.
  4624.     fLastClickPart = inDesk;
  4625. }
  4626.  
  4627. //----------------------------------------------------------------------------------------
  4628. // TApplication::SetTarget: 
  4629. //----------------------------------------------------------------------------------------
  4630. #pragma segment MAApplicationRes
  4631.  
  4632. void TApplication::SetTarget(TEventHandler* newTarget)
  4633. {
  4634.     if (newTarget == NULL)
  4635.     {
  4636.         newTarget = this;
  4637. #if qDebug
  4638.         ProgramBreak("In TApplication.SetTarget…  you're setting the global target to NULL!");
  4639. #endif
  4640.  
  4641.     }
  4642.  
  4643.     if (newTarget != fTarget)
  4644.     {
  4645.         fTarget->ResignedTarget();
  4646.         fTarget = newTarget;
  4647.         fTarget->BecameTarget();
  4648.         this->InvalidateMouseRegions();
  4649.     }
  4650. } // TApplication::SetTarget 
  4651.  
  4652. //----------------------------------------------------------------------------------------
  4653. // TApplication::SetUndoText: 
  4654. //----------------------------------------------------------------------------------------
  4655. #pragma segment MAApplicationRes
  4656.  
  4657. void TApplication::SetUndoText(Boolean cmdDone,
  4658.                                CommandNumber aCommandNumber)
  4659. {
  4660.     if ((fUndoState != cmdDone) || (fUndoCommand != aCommandNumber))
  4661.     {
  4662.         short newMenuState;
  4663.  
  4664.         if (aCommandNumber == cCantUndo)
  4665.             newMenuState = bzCantUndo;
  4666.         else if (cmdDone)
  4667.             newMenuState = bzUndo;
  4668.         else
  4669.             newMenuState = bzRedo;
  4670.  
  4671.         CStr255 undoName;
  4672.         GetIndString(undoName, kIDBuzzString, newMenuState);
  4673.  
  4674.         short preCmdName;
  4675.         short constChars;
  4676.         if (ParseTitleTemplate(undoName, preCmdName, constChars))
  4677.         {
  4678.             CStr255 cmdName = gEmptyString;
  4679.             if ((aCommandNumber != cNoCommand) && (aCommandNumber != cCantUndo))
  4680.                 CommandToName(aCommandNumber, cmdName);
  4681.             SubstituteInTitle(undoName, cmdName, preCmdName, constChars);
  4682.         }
  4683.  
  4684.         SetCommandName(cUndo, undoName);
  4685.  
  4686.         fUndoState = cmdDone;
  4687.         fUndoCommand = aCommandNumber;
  4688.     }
  4689. } // TApplication::SetUndoText 
  4690.  
  4691. //----------------------------------------------------------------------------------------
  4692. // TApplication::SetupTheMenus: 
  4693. //----------------------------------------------------------------------------------------
  4694. #pragma segment MAApplicationRes
  4695.  
  4696. void TApplication::SetupTheMenus()
  4697. {
  4698.     if (this->IsFrontProcess() && (MenusHavePendingUpdate()))
  4699.     {
  4700.         gMenuBarManager->Reset();                // reset the preferred menubar
  4701.  
  4702.         PerformMenuSetup(&DoSetupTheMenus, (void *)kNoStaticLink);
  4703.         
  4704.         gMenuBarManager->InstallPreferredMenus();
  4705.         if (MenusHavePendingUpdate())
  4706.         {
  4707.             // Add the debugger menu
  4708.             if (qDebug || qPerform)
  4709.                 AddMenuBar(kMBarDebug, false);
  4710.  
  4711.             // Recurse to get the menus correctly setup
  4712.             this->SetupTheMenus();
  4713.         }
  4714.     }
  4715. } // TApplication::SetupTheMenus 
  4716.  
  4717. //----------------------------------------------------------------------------------------
  4718. // TApplication::GetStandardFileParameters: 
  4719. //----------------------------------------------------------------------------------------
  4720. #pragma segment MAOpen
  4721.  
  4722. void TApplication::GetStandardFileParameters(CommandNumber itsCommandNumber,
  4723.                                              ProcPtr& fileFilter,
  4724.                                              TypeListHandle& typeList,
  4725.                                              short& dlgID,
  4726.                                              CPoint& where,
  4727.                                              ProcPtr& dlgHook,
  4728.                                              ProcPtr& modalFilter,
  4729.                                              Ptr& activeList,
  4730.                                              ProcPtr& activateProc,
  4731.                                              void*& yourDataPtr)
  4732. {
  4733.     if (qNeedsAliasMgr || gConfiguration.hasAliasMgr)
  4734.     {
  4735.         dlgID = sfGetDialogID;
  4736.         where = CPoint(-1, -1);
  4737.     }
  4738.     else
  4739.     {
  4740.         dlgID = getDlgID;                        // getDlgID defined by Standard File 
  4741.         DialogTHndl dlogTemplate = (DialogTHndl)(GetResource('DLOG', dlgID));
  4742.         if (dlogTemplate)
  4743.         {
  4744.             CRect dialogRect = (*dlogTemplate)->boundsRect;
  4745.             CenterRectOnScreen(dialogRect, true, true, true);
  4746.             where = dialogRect[topLeft];
  4747.         }
  4748.         else
  4749.             where = CPoint(100, 100);
  4750.     }
  4751.  
  4752.     this->GetFileTypeList(itsCommandNumber, typeList);
  4753.  
  4754.     fileFilter = NULL;
  4755.  
  4756.     dlgHook = NULL;
  4757.  
  4758.     modalFilter = (ProcPtr)gModalFilterYDProcPtr;
  4759.  
  4760.     activeList = NULL;
  4761.  
  4762.     activateProc = NULL;
  4763.     
  4764.     yourDataPtr = NULL;
  4765. } // TApplication::GetStandardFileParameters 
  4766.  
  4767. //----------------------------------------------------------------------------------------
  4768. // TApplication::GetFileTypeList: 
  4769. //----------------------------------------------------------------------------------------
  4770. #pragma segment MAOpen
  4771.  
  4772. void TApplication::GetFileTypeList(CommandNumber,
  4773.                                    TypeListHandle& typeList)
  4774. {
  4775.     typeList = (TypeListHandle) NewPermHandle(4);
  4776.     (*typeList)[0] = fMainFileType;
  4777. } // TApplication::GetFileTypeList 
  4778.  
  4779. //----------------------------------------------------------------------------------------
  4780. // TApplication::ShowError: 
  4781. //----------------------------------------------------------------------------------------
  4782. #pragma segment MAError
  4783.  
  4784. void TApplication::ShowError(OSErr error, long message)
  4785. {
  4786.     ErrorAlert(error, message);
  4787. } // TApplication::ShowError 
  4788.  
  4789. //----------------------------------------------------------------------------------------
  4790. // TApplication::SpaceIsLowAlert: 
  4791. //----------------------------------------------------------------------------------------
  4792. #pragma segment MAApplicationRes
  4793.  
  4794. void TApplication::SpaceIsLowAlert()
  4795. {
  4796. #if !qPowerPC
  4797.     if (fEventLevel == 1)                    // Don't unload segs if nested event handling
  4798.         UnloadAllSegments();
  4799. #endif
  4800.     
  4801.     // Show 'space is low' alert only after ever fLowSpaceInterval ticks. 
  4802.     if ((fLowSpaceInterval > 0) && this->IsFrontProcess())
  4803.     {
  4804.         if (TickCount() > fNextSpaceMessage)
  4805.         {
  4806.             gInhibitNestedHandling = true;    // Don't tell em again from the alert 
  4807.             StdAlert(phSpaceIsLow);
  4808.             fNextSpaceMessage = TickCount() + fLowSpaceInterval;
  4809.         }
  4810.     }
  4811. } // TApplication::SpaceIsLowAlert 
  4812.  
  4813. //----------------------------------------------------------------------------------------
  4814. // TApplication::DoSetCursor: 
  4815. //----------------------------------------------------------------------------------------
  4816. #pragma segment MAApplicationRes
  4817.  
  4818. void TApplication::DoSetCursor(CPoint globalMouse,
  4819.                                RgnHandle cursorRegion)
  4820. {
  4821.     this->GetDefaultCursorRegion(globalMouse, cursorRegion);
  4822.     SetCursor(&(qd.arrow));
  4823. } // TApplication::DoSetCursor 
  4824.  
  4825. //----------------------------------------------------------------------------------------
  4826. // TApplication::HandleCursor: 
  4827. //----------------------------------------------------------------------------------------
  4828. #pragma segment MAApplicationRes
  4829.  
  4830. void TApplication::HandleCursor(CPoint globalMouse,
  4831.                                 RgnHandle cursorRegion)
  4832. {
  4833.     WindowPtr aWMgrWindow;
  4834.     if (FindWindow(globalMouse, &aWMgrWindow) == inContent)
  4835.     {
  4836.         TWindow * cursorWindow = this->WMgrToWindow(aWMgrWindow);
  4837.         if ((cursorWindow) && cursorWindow->HandlesCursor())
  4838.         {
  4839.             VPoint windowVPt(globalMouse);
  4840.             cursorWindow->SuperToLocal(windowVPt);
  4841.             cursorWindow->HandleCursor(windowVPt, fCursorRegion);
  4842.  
  4843.             // Convert cursor region from window coords to global coords 
  4844.             cursorWindow->LocalToSuperRegion(cursorRegion);
  4845.         }
  4846.     }
  4847. } // TApplication::HandleCursor 
  4848.  
  4849. //----------------------------------------------------------------------------------------
  4850. // TApplication::TrackCursor: 
  4851. //----------------------------------------------------------------------------------------
  4852. #pragma segment MAApplicationRes
  4853.  
  4854. void TApplication::TrackCursor(CPoint globalMouse)
  4855. {
  4856. #if qDebugMsg
  4857.     if (PtInRgn(globalMouse, fCursorRegion))
  4858.     {
  4859.  
  4860.         if (gIntenseDebugging)
  4861.             fprintf(stderr, "cursor is in cursor region\n");
  4862.  
  4863.     }
  4864. #endif
  4865.  
  4866.     this->InvalidateCursorRgn();
  4867.  
  4868.     // Find out if the cursor is in a window which handles the cursor, and if so, call
  4869.     // HandleCursor to allow a view to claim the cursor, and compute a region
  4870.     this->HandleCursor(*((CPoint *)&globalMouse), fCursorRegion);
  4871.  
  4872.     if (EmptyRgn(fCursorRegion))
  4873.         this->DoSetCursor(globalMouse, fCursorRegion);
  4874.  
  4875.     // Make sure the cursorpoint is included 
  4876.     PtAndRgn(globalMouse, fCursorRegion);
  4877.  
  4878. #if qDebugMsg
  4879.     if (gIntenseDebugging)
  4880.         if (fCursorRegion == NULL)
  4881.             fprintf(stderr, "fCursorRegion is NULL\n");
  4882. #endif
  4883.  
  4884.     if (qDebug && gIntenseDebugging &&!PtInRgn(globalMouse, fCursorRegion))
  4885.     {
  4886.         CRect bBox = (*fCursorRegion)->rgnBBox;
  4887.         fprintf(stderr, "Whoops, cursor region was not correctly calculated.\n");
  4888.         fprintf(stderr, "global cursor = ", (char*)globalMouse);
  4889.         fprintf(stderr, "  (*fCursorRegion)->rgnBBox = ", (char*) bBox);
  4890.         fprintf(stderr, "\n");
  4891.         ProgramBreak("The cursor is not in the cursor region at end of TApplication.TrackCursor!");
  4892.     }
  4893. } // TApplication::TrackCursor 
  4894.  
  4895. //----------------------------------------------------------------------------------------
  4896. // TApplication::DoShowHelp: 
  4897. //----------------------------------------------------------------------------------------
  4898. #pragma segment MAApplicationRes
  4899.  
  4900. void TApplication::DoShowHelp(CPoint globalMouse,
  4901.                               RgnHandle helpRegion)
  4902. {
  4903.     if (HMIsBalloon())
  4904.     {
  4905.         OSErr err = HMRemoveBalloon();
  4906.         if (err != hmNoBalloonUp)
  4907.             FailOSErr(err);
  4908.     }
  4909.     this->GetDefaultHelpRegion(globalMouse, helpRegion);
  4910. } // TApplication::DoShowHelp 
  4911.  
  4912. //----------------------------------------------------------------------------------------
  4913. // TApplication::HandleHelp: 
  4914. //----------------------------------------------------------------------------------------
  4915. #pragma segment MAApplicationRes
  4916.  
  4917. void TApplication::HandleHelp(CPoint globalMouse,
  4918.                               RgnHandle helpRegion)
  4919. {
  4920.     WindowPtr aWMgrWindow;
  4921.     if (FindWindow(globalMouse, &aWMgrWindow) == inContent)
  4922.     {
  4923.         TWindow * helpWindow = this->WMgrToWindow(aWMgrWindow);
  4924.         if ((helpWindow) && helpWindow->HandlesHelp())
  4925.         {
  4926.             VPoint windowVPt(*((CPoint *)&globalMouse));
  4927.             helpWindow->SuperToLocal(windowVPt);
  4928.             helpWindow->HandleHelp(windowVPt, helpRegion);
  4929.  
  4930.             // Convert helpRegion region from window coords to global coords 
  4931.             helpWindow->LocalToSuperRegion(helpRegion);
  4932.         }
  4933.     }
  4934. } // TApplication::HandleHelp 
  4935.  
  4936. //----------------------------------------------------------------------------------------
  4937. // TApplication::TrackHelp: 
  4938. //----------------------------------------------------------------------------------------
  4939. #pragma segment MAApplicationRes
  4940.  
  4941. void TApplication::TrackHelp(CPoint globalMouse)
  4942. {
  4943.  
  4944. #if qDebugMsg
  4945.     if (PtInRgn(globalMouse, fHelpRegion))
  4946.     {
  4947.  
  4948.         if (gIntenseDebugging)
  4949.             fprintf(stderr, "cursor is in help region\n");
  4950.     }
  4951. #endif
  4952.  
  4953.     this->InvalidateHelpRgn();
  4954.  
  4955.     // Find out if the cursor is in a window which handles help, and if so, call
  4956.     // HandleHelp to allow some subview to show help, and compute a region
  4957.     this->HandleHelp(*((CPoint *)&globalMouse), fHelpRegion);
  4958.  
  4959.     if (EmptyRgn(fHelpRegion))
  4960.         this->DoShowHelp(globalMouse, fHelpRegion);
  4961.  
  4962.     // Make sure the cursorpoint is included 
  4963.     PtAndRgn(globalMouse, fHelpRegion);
  4964.  
  4965. #if qDebugMsg
  4966.     if (gIntenseDebugging)
  4967.         if (fHelpRegion == NULL)
  4968.             fprintf(stderr, "fHelpRegion is NULL\n");
  4969. #endif
  4970.  
  4971.     if (qDebug && gIntenseDebugging &&!PtInRgn(globalMouse, fHelpRegion))
  4972.     {
  4973.         CRect bBox = (*fHelpRegion)->rgnBBox;
  4974.         fprintf(stderr, "Whoops, help region was not correctly calculated.\n");
  4975.         fprintf(stderr, "global cursor = ", (char*)globalMouse);
  4976.         fprintf(stderr, "  (*fHelpRegion)->rgnBBox = ", (char*) bBox);
  4977.         fprintf(stderr, "\n");
  4978.         ProgramBreak("The cursor is not in the help region at end of TApplication.TrackHelp!");
  4979.     }
  4980.  
  4981. } // TApplication::TrackHelp 
  4982.  
  4983. //----------------------------------------------------------------------------------------
  4984. // TApplication::TrackMouse: 
  4985. //----------------------------------------------------------------------------------------
  4986. #pragma segment MADoCommand
  4987.  
  4988. TTracker* TApplication::TrackMouse(const VPoint& theMouse,
  4989.                                    CPoint hysteresis,
  4990.                                    TTracker* theCommand)
  4991. {
  4992.     TTracker* currentTracker = NULL;    // so failure handler works
  4993.     VOLATILE(currentTracker);            // so failure handler works
  4994.     VOLATILE(theCommand);                // so failure handler works (theCommand is changed)
  4995.  
  4996.     FailInfo fi;
  4997.     Try(fi)
  4998.     {
  4999.         currentTracker = theCommand->HandleTrackBegin(theMouse, hysteresis);
  5000.         theCommand = NULL;                // so failure handler works
  5001.  
  5002.         while (currentTracker && !currentTracker->IsDoneTracking())
  5003.             if (this->IsFrontProcess())
  5004.                 currentTracker = currentTracker->HandleTrackContinue();
  5005.  
  5006.         if (currentTracker)
  5007.             currentTracker = currentTracker->HandleTrackEnd();
  5008.  
  5009.         fi.Success();
  5010.     }
  5011.     else
  5012.     {
  5013.         if (theCommand)
  5014.         {
  5015.             theCommand->Completed();
  5016.  
  5017.             if (theCommand->ShouldFreeOnCompletion())
  5018.             {
  5019.                 if (theCommand == theCommand->fContext->fLastCommand)
  5020.                         theCommand->fContext->fLastCommand = NULL;        // be sure to clear reference 
  5021.     
  5022.                 theCommand = (TTracker*) FreeIfObject(theCommand);
  5023.             }
  5024.         }
  5025.  
  5026.         if (currentTracker)
  5027.         {
  5028.             currentTracker->Completed();
  5029.  
  5030.             if (currentTracker->ShouldFreeOnCompletion())
  5031.             {
  5032.                 if (currentTracker == currentTracker->fContext->fLastCommand)
  5033.                         currentTracker->fContext->fLastCommand = NULL;        // be sure to clear reference 
  5034.     
  5035.                 currentTracker = (TTracker*) FreeIfObject(currentTracker);
  5036.             }
  5037.         }
  5038.  
  5039.         fi.ReSignal();
  5040.     }
  5041.  
  5042.     return currentTracker;
  5043. } // TApplication::TrackMouse 
  5044.  
  5045. //----------------------------------------------------------------------------------------
  5046. // TApplication::UpdateAllWindows: 
  5047. //----------------------------------------------------------------------------------------
  5048. #pragma segment MAApplicationRes
  5049.  
  5050. void TApplication::UpdateAllWindows()
  5051. {
  5052.     TToolboxEvent * event;
  5053.  
  5054.     ++fEventLevel;
  5055.     while ((event = this->GetEvent(updateMask + activMask, 0, NULL)) != NULL)
  5056.         event->Process();
  5057.     --fEventLevel;
  5058. } // TApplication::UpdateAllWindows 
  5059.  
  5060. //----------------------------------------------------------------------------------------
  5061. // TApplication::DoMakeViewServer: 
  5062. //----------------------------------------------------------------------------------------
  5063. #pragma segment MAInit
  5064.  
  5065. void TApplication::DoMakeViewServer()
  5066. {
  5067.     TViewServer * aViewServer = new TViewServer;
  5068.     aViewServer->IViewServer();                    // assigns the global reference
  5069. } // TApplication::DoMakeViewServer 
  5070.  
  5071. //----------------------------------------------------------------------------------------
  5072. // TApplication::WMgrToWindow: 
  5073. //----------------------------------------------------------------------------------------
  5074. #pragma segment MAApplicationRes
  5075.  
  5076. TWindow* TApplication::WMgrToWindow(WindowPtr aWindowPtr)
  5077. {
  5078.     // just uses the global routine in UWindow
  5079.     return ::WMgrToWindow(aWindowPtr);
  5080. } // TApplication::WMgrToWindow 
  5081.  
  5082.  
  5083. //----------------------------------------------------------------------------------------
  5084. // TApplication::GetApplicationName: 
  5085. //----------------------------------------------------------------------------------------
  5086. #pragma segment MAWriteFile
  5087.  
  5088. void TApplication::GetApplicationName(CStr255& theName)
  5089. {
  5090.     if (qNeedsProcessMgr || gConfiguration.hasProcessMgr)
  5091.     {
  5092.         FailInfo fi;
  5093.         Try(fi)
  5094.         {
  5095.             ProcessInfoRec info;
  5096.             info.processInfoLength = sizeof(ProcessInfoRec);
  5097.             info.processName = theName;
  5098.             info.processAppSpec = NULL;
  5099.             FailOSErr(GetProcessInformation(&fProcessNumber, &info));
  5100.             fi.Success();
  5101.         }
  5102.         else
  5103.         {
  5104. #if qDebug
  5105.             ProgramBreak("TApplication::GetApplicationName() failed!");
  5106. #endif
  5107.             // no need to fail completely, just return generic string
  5108.             theName = "<Application>";
  5109.         }
  5110.     }
  5111.     else 
  5112.     {
  5113.         theName = LMGetCurApName();
  5114.     }
  5115. } // TApplication::GetApplicationName 
  5116.